feedwall
feedwall

Reputation: 1574

what is the best way to check in C# .NET if a directory has access to list files or a unauthorized access exception would rise

how would I check in the best way in .NET 2.0 C# if I have access to a specified directory for listing top directory files e.g. a system directory or system volume information folder etc. My code for it looks now like this, but I think it is not the best way to check for it since it produces an exception each time which is handled by the check function and returning based on it a result.

I would like to use a function which doesn't throw an error to check if in the specified directory is access to list files or maybe my code can be improved or optimized. I might have to check through a thousand directories if exists an access or not. Raising thousand exceptions might cause a problem, but I don't know.

//here my code using System.IO;

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(DirectoryCanListFiles("C:\\Windows\\Prefetch").ToString());
}

public static bool DirectoryCanListFiles(string DirectoryPath)
{
    try
    {
        Directory.GetFiles(DirectoryPath, "*", SearchOption.TopDirectoryOnly);
    }
    catch { return false; }
    return true;
}

Upvotes: 2

Views: 2244

Answers (1)

Abhijeet
Abhijeet

Reputation: 13856

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

However for some reason out there, 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;
}

Upvotes: 2

Related Questions