Applying Permissions on any Windows Folder using C#

Applying permissions on folders/directories in Windows is one of the things developers want to control with their applications. Today we are going to look at how can we create such an application in C# which can define any kind of permission to any user account in Windows environment.

Start Visual Studio and create a new C# Windows application. Name it DirectoryPermission and Create an interface which looks similar to the one below:

1. Change the text of your window to Folder Permission or any other you like.  

2. Drag two labels, two buttons, 1 textbox and 1 combo box on the form. Name the buttons as SelectDirectorybtn and Permissionbtn and leave the names of others as default. 

3. Now we need to add two references, for that right-click your project root and select Add reference.


4. From the Add Reference Menu, add following two highlighted references.

Both of these references actually help us interact with Operating System’s account management and queries.

5. Right click on your Windows Form and Select View Code. 

6. First of all we will define the references that we added in Step 4. We’ll also add System.IO and System.Security.AccessControl

   1:  using System.IO;
   2:  using System.Security.AccessControl;
   3:  using System.Management;
   4:  using System.Management.Instrumentation;


7. Now we are going to define a method which will fill our combobox with names of all user account.

   1:  public void GetUsers()
   2:  {
   3:          // This query will query for all user account names in our current Domain
   4:          SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "Domain='" 
                             + System.Environment.UserDomainName.ToString() + "'");
   6:           try
   7:           {
   8:                     // Searching for available Users
   9:                      ManagementObjectSearcher mSearcher = new 
  11:                      foreach (ManagementObject mObject in mSearcher.Get())
  12:                      {
  13:                              // Adding all user names in our combobox
  14:                              comboBox1.Items.Add(mObject["Name"]);
  15:                      }
  16:           }
  17:           catch (Exception ex)
  18:           {
  19:                      MessageBox.Show(ex.ToString());
  20:           }
  21:  }

Note: System.Environment.UserDomainName is going to deliver us our current domain.


8. In order to make the above method effective, we need to modify our form constructor.

   1:  public Form1()
   2:  {
   3:              InitializeComponent();
   4:              GetUsers();
   5:  }


9. Now we’ll go back to our design window and double click Select Directory button to define its clicking event. Change the definition to following;

   1:  private void SelectDirectorybtn_Click(object sender, EventArgs e)
   2:  {
   3:             // creating a new instance fot FolderBrowsingDialog 
                                    to provide user capability to select target Folder
   4:             FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
   6:             // showing dialog
   7:             myFolderBrowserDialog.ShowDialog();
   9:             // Show the path of selected directory in our text Box 
  10:             textBox1.Text myFolderBrowserDialog.SelectedPath.ToString();
  11:  }


10. Move back to your design view and add a Click event to the second button i.e. Make Unreadable, double click it to modify the event.

   1:  private void Permissionbtn_Click(object sender, EventArgs e)
   2:  {
   3:             // retrieving the directory information
   4:             DirectoryInfo myDirectoryInfo = new DirectoryInfo(textBox1.Text);
   6:             // Get a DirectorySecurity object that represents the 
   7:             // current security settings.
   8:             DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
   9:             string User = System.Environment.UserDomainName + "\\" + 
  11:             // Add the FileSystemAccessRule to the security settings. 
                 // FileSystemRights is a big list we are current using Read property but you 
                 // can alter any other or many sme of which are:
  12:            // Create Directories: for sub directories Authority
  13:            // Create Files: for files creation access in a particular folder
  14:            // Delete: for deletion athority on folder
  15:            // Delete Subdirectories and files: for authority of deletion over 
                  //subdirectories and files
  16:            // Execute file: For execution accessibility in folder
  17:            // Modify: For folder modification
  18:            // Read: For directory opening
  19:            // Write: to add things in directory
  20:            // Full Control: For administration rights etc etc
  22:            // Also AccessControlType which are of two kinds either “Allow” or “Deny” 
  23:            myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, 
                                              FileSystemRights.Read, AccessControlType.Deny));
  25:            // Set the new access settings. 
  26:            myDirectoryInfo.SetAccessControl(myDirectorySecurity);
  28:           // Showing a Succesfully Done Message
  29:           MessageBox.Show("Permissions Altered Successfully");
  30:  }

That’s it. Compile and execute the application to test results. If you have any queries feel free to ask… Cheers! 🙂