how to check if specific user having access to a shared folder location using C#

前端 未结 1 985
南笙
南笙 2021-01-25 12:55

We have a scenario in our client project where the client application saves and tries to fetch files from a shared folder location , which is a virtual shared folder. But we hav

相关标签:
1条回答
  • 2021-01-25 13:27

    the way I believe best to check the permission, is try to access the directory (read/write/list) & catch the UnauthorizedAccessException.

    If you want to check permissions, following code should satisfy your need. You need to read Access Rules for the directory.

    private bool DirectoryCanListFiles(string folder)
    {
        bool hasAccess = false;
        //Step 1. Get the userName for which, this app domain code has been executing
        string executingUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        NTAccount acc = new NTAccount(executingUser);
        SecurityIdentifier secId = acc.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
    
        DirectorySecurity dirSec = Directory.GetAccessControl(folder);
    
        //Step 2. Get directory permission details for each user/group
        AuthorizationRuleCollection authRules = dirSec.GetAccessRules(true, true, typeof(SecurityIdentifier));                        
    
        foreach (FileSystemAccessRule ar in authRules)
        {
            if (secId.CompareTo(ar.IdentityReference as SecurityIdentifier) == 0)
            {
                var fileSystemRights = ar.FileSystemRights;
                Console.WriteLine(fileSystemRights);
    
                //Step 3. Check file system rights here, read / write as required
                if (fileSystemRights == FileSystemRights.Read ||
                    fileSystemRights == FileSystemRights.ReadAndExecute ||
                    fileSystemRights == FileSystemRights.ReadData ||
                    fileSystemRights == FileSystemRights.ListDirectory)
                {
                    hasAccess = true;
                }
            }
        }
        return hasAccess;
    }
    
    0 讨论(0)
提交回复
热议问题