简体   繁体   中英

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

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 have been facing issues with a specific application user id losing access to that shared folder. So we need help in pre advance checking if the access is present for that user id on that shared folder location . So thinking of an application to be developed in C# or vb.net to check for that user access .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM