4. Checking File and Directory Permissions
When all is
said and done, however, the real issue is determining what rights a
user has to a resource such as a file or directory. Nevertheless, the principles apply equally well to any resource. Before a
user or other entity can access a resource, it's important to have the
required rights. The following sections show an example of how to
perform this task.
4.1. Configuring the Check Permission Example
This example begins with a Windows Forms application. You add the controls shown in Figure 1. In addition, you need to provide the following using statements:
using System.Security.AccessControl;
using System.IO;
using System.Security.Principal;
4.2. Writing the Check Permission Code
The principle behind this example is relatively
simple. If a user has a particular permission, the system sets a flag
within the DACL. The .NET Framework encompasses these flags within a
structure called a FileSystemAccessRule. Listing 5 provides details on how this flag system works.
Example 5. Checking file or directory permissions
private void btnCheck_Click(object sender, EventArgs e)
{
// Create a file security object for the target file.
FileSecurity FS = new FileSecurity(
Application.StartupPath + @"\Temp.TXT",
AccessControlSections.Access);
// Obtain the access rules for the file.
AuthorizationRuleCollection AccessRules =
FS.GetAccessRules(true, true,
typeof(NTAccount));
// Create a string that contains the rule data.
String RuleHeading = "";
// Process the access rules.
foreach (FileSystemAccessRule AR in AccessRules)
{
// Add the principal name to the string.
RuleHeading = AR.IdentityReference.Value.ToString();
// Determine whether the permission is inherited.
if (AR.IsInherited)
RuleHeading += " (Inherited)";
else
RuleHeading += " (Not Inherited)";
// Output the rule heading.
lstPermissions.Items.Add(RuleHeading);
// Obtain a list of permissions.
if (AR.FileSystemRights.HasFlag(FileSystemRights.AppendData))
lstPermissions.Items.Add("\tAppend Data");
if (AR.FileSystemRights.HasFlag(FileSystemRights.ChangePermissions))
lstPermissions.Items.Add("\tChange Permissions");
if (AR.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories))
lstPermissions.Items.Add("\tCreate Directories");
if (AR.FileSystemRights.HasFlag(FileSystemRights.CreateFiles))
lstPermissions.Items.Add("\tCreate Files");
... Other Permission Statements Clipped ...
}
}
|
The example begins by creating a new FileSecurity object, FS. The FileSecurity object contains information about a particular resource. In this case, it contains the AccessControlSections.Access flags. If you select one of the other values, such as AccessControlSections.Audit, you may have to have administrator privileges, but the access rules are open to anyone with the proper rights. The FileSecurity() constructor requires both the resource you want to use, Temp.TXT in this case, and the level of flags you want to access.
Within the FS are the flags you want to access. In order to access these flags, you create an AuthorizationRuleCollection, AccessRules. It's possible to format the rules in several ways. The example obtains both explicit rights and inherited rights using an NTAccount data type.
At this point, the example examines each of the rules within the AuthorizationRuleCollection individually using a for loop. Each of the FileSystemAccessRule objects, AR,
provides a principal name (the account with access), whether the access
is explicit (defined in particular for this object) or inherited, and a
list of flags. The HasFlag() method makes it easy to determine whether the user has a particular right. Figure 13 shows typical output for this example.
5. Changing File and Directory Permissions
In general, an administrator is going to set resource
permissions on a system, including file and directory permissions.
However, there are times when an application needs to set permissions.
Fortunately, changing file and directory permissions is another area
that Microsoft has added to the .NET Framework to make it easier to
manage this resource. The following sections describe the Modify
Permission example, which shows the basics of changing a file
permission. You can easily extend this example to work with other kinds
of resources.
5.1. Configuring the Modify Permission Example
This example begins with a Windows Forms application that has a single button, btnChange. You click the button to add a user to the permission list for the test file, Test.TXT. The example also requires that you add the following using statements to the code:
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;
5.2. Writing the Modify Permission Code
Modifying a permission involves gaining access to the
file and adding a rule to it. The rule provides an account, the kind of
access, and whether to allow or deny the access. Listing 6 shows the code required for this example.
Example 6. Modifying file or directory permissions
private void btnChange_Click(object sender, EventArgs e)
{
// Create a file security object for the target file.
FileSecurity FS = File.GetAccessControl(
Application.StartupPath + @"\Temp.TXT");
// Create a new rule.
FileSystemAccessRule Rule = new FileSystemAccessRule(
new NTAccount(@"BUILTIN\Users"),
FileSystemRights.Write,
AccessControlType.Allow);
// Add the rule to the file security object.
FS.AddAccessRule(Rule);
// Save the rule to the file.
File.SetAccessControl(
Application.StartupPath + @"\Temp.TXT", FS);
// Display a success message.
MessageBox.Show("Change Succeeded!");
}
|
The code begins by creating a FileSecurity object, FS, that provides access to the permissions for Temp.TXT. Remember that this code is actually changing the DACL for Temp.TXT. To provide better control over the process, you could include an AccessControlSections.Access enumeration member as a second argument.
To add a new user to the permissions, the code creates a FileSystemAccessRule, Rule,
that includes the Users built-in account, the ability to write to the
file, and an Allow permission. Notice that you must provide an account
type, which is going to be NTAccount() in most situations. The code calls the AddAccessRule() method to actually add the rule to FS.
At this point, the code calls File.SetAccessControl() to change the DACL of Temp.TXT. This method requires that you provide the filename as the first input and the FileSecurity
object as the second input. Because there isn't any notification that
the process has succeeded, the code displays a simple success message. Figure 14 shows the modified permissions for Temp.TXT.
Notice that the Write right has a dark checkmark, showing that it's
explicitly set, while the Read & Execute and Read rights use lighter
checkmarks to show that they're inherited.
Never attempt to change file permissions
while the file is open using a file object in Windows 7. You'll receive
an "Attempted to perform an unauthorized operation" error message from
the application. Absolutely nothing you can do will change the message
or tell you the message source. Your code will look correct and you'll
even find examples of it online (see http://msdn.microsoft.com/magazine/cc163885.aspx), but it won't work. Always change permissions with the file closed and using the File.SetAccessControl() static method directly. |