How to find out if a user can read and list catalog files

I have a folder on my computer and I used DirectoryInfo to get all the files in this folder. But it uses my user account. I have to use the permissions of another user account, and I need to know if this other account can read and list files in this folder.

Here is the code I wrote to get the files:

DirectoryInfo Folder = new DirectoryInfo(folderName);
FileInfo[] Files = Folder.GetFiles(search, SearchOption.TopDirectoryOnly);

I was expecting a way to do something like this:

DirectoryInfo Folder = new DirectoryInfo(folderName, UserCredentials);

And if this user does not have permission, this line excludes or can verify the rights of the user.

thanks...

+4
source share
3 answers

:

using System.IO;
using System.Security.AccessControl;
public static FileSystemRights GetDirectoryPermissions(string user, string domainName, string folderPath)
{
    if (!Directory.Exists(folderPath))
    {
        return (0);
    }

    string identityReference = ((domainName + @"\" + user) as string).ToLower();
    DirectorySecurity dirSecurity = Directory.GetAccessControl(folderPath, AccessControlSections.Access);
    foreach (FileSystemAccessRule fsRule in dirSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
    {
        if (fsRule.IdentityReference.Value.ToLower() == identityReference)
        {
            return (fsRule.FileSystemRights);
        }
    }
    return (0);
}

, - , 0. , .

+3

.

public bool CheckFolderPermissions(string folderPath)
{
 WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
 var domainAndUser = currentUser.Name;
 DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
 DirectorySecurity dirAC =     dirInfo.GetAccessControl(AccessControlSections.All);
 AuthorizationRuleCollection rules = dirAC.GetAccessRules(true, true, typeof(NTAccount));

 foreach (AuthorizationRule rule in rules)
 {
     if (rule.IdentityReference.Value.Equals(domainAndUser, StringComparison.CurrentCultureIgnoreCase))
     {
         if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
         return true;
     }
  }
 return false;
}
+2

I believe that you will need to call the SetAccessControl method on the DirectoryInfo object to accomplish this. For more information about this method, see https://msdn.microsoft.com/en-us/library/system.io.directoryinfo.setaccesscontrol(v=vs.110).aspx .

+1
source

Source: https://habr.com/ru/post/1617117/


All Articles