0

I'm trying to get right for a folder. The purpose is to create a file inside this folder when i ask my program to create this file. I tried almost everything and it still don't work.

try
{

   DirectorySecurity ds = Directory.GetAccessControl(path);

   foreach (FileSystemAccessRule rule in ds.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)))
   {
      if ((rule.FileSystemRights & FileSystemRights.CreateFiles) > 0 /*== FileSystemRights.CreateFiles)*/)
         return true;
   }
}
catch (UnauthorizedAccessException e)
{
   return false;
}
return false;

My problem is: The FileSystemAccessRule said that I have the permissions but when I want to create my file, "unauthorizedexception" exception appears.

I tried to use a DirectoryInfo, like that:

DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity ds = di.GetAccessControl();

instead of to use the "Directory" object directly. Plus, i was thinking that my problem was concerning the GetAccessRules, so I tried to use the SecurityIdentifier and also NTAccount, both said that I have all the right on this folder (FullControl) whereas at the end, i don't have any right. And of course my path is good, I checked it.

Someone knows another method to get the right on a folder, or if I do something wrong, a bit of help will be a pleasure.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • So if I understand correctly you want to gain rights to a folder using this code? – Patrick Hofman Mar 26 '14 at 10:18
  • I just want to get the rights of the folder. If my function return true, yes I can create my file, if not, I throw a message. Today, apparently I have all the rights on the folder (I used "FullControl") because the function return true. However, when I want to create my file, access denied. – user3463516 Mar 27 '14 at 12:39

1 Answers1

0

I think the problem with your code is that is does not check on the specific users which have access. GetAccessControl gets a list of ALL users that have any access rule applied to the folder, not just YOU.

There is an excellent answer already here how to do the proper checking: Checking for directory and file write permissions in .NET

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325