3

I have this code in C# for giving full control to any file, it works excellent.

But how can I give full control to any directory?

Code to give full access to a file:

string fileName = @"d:\MyFile.mdb";
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(fileName, fSecurity);
gnat
  • 6,213
  • 108
  • 53
  • 73
Gali
  • 14,511
  • 28
  • 80
  • 105
  • 1
    Possible duplicate: http://stackoverflow.com/questions/8944765/c-sharp-set-directory-permissions-for-all-users-in-windows-7 – Bridge May 21 '12 at 08:18

2 Answers2

3

In exactly the same way, but using Directory.GetAccessControl instead of File.GetAccessControl:

DirectorySecurity dirSec = Directory.GetAccessControl("C:\\temp");
dirSec.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl("c:\\temp", dirSec);
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
  • i try this on C:\inetpub\wwwroot\MyWS it adds the Everyone user but no full control , what can be the problem ? – Gali May 21 '12 at 08:45
  • You're launching program not as Administrator? – Anton May 21 '12 at 12:41
  • i think that i Administrator, but if not - is there any way to run the program as Administrator ? – Gali May 21 '12 at 13:08
  • Getting closer. now added the "Everyone" group to the folder, but the permissions show up blank; nothing granted. – Gali May 21 '12 at 13:44
0

Here's an example:

        DirectoryInfo myDirectoryInfo = new DirectoryInfo(@"C:\Dir1\");

        DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

        string User = System.Environment.UserDomainName + "\\" + "Everyone"; 

        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, 
                                          FileSystemRights.FullControl, 
                                          AccessControlType.Deny)); 

        myDirectoryInfo.SetAccessControl(myDirectorySecurity);
Shai
  • 25,159
  • 9
  • 44
  • 67