2

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;
}
feedwall
  • 1,473
  • 7
  • 28
  • 48
  • I dont see anyother way to do that check similar [http://stackoverflow.com/questions/753120](http://stackoverflow.com/questions/753120/how-can-my-c-sharp-app-test-whether-the-user-has-read-access-to-a-network-shar) – Nilesh Aug 10 '13 at 16:31
  • What would possibly be the point in enumerating files from the Windows Prefetch directory? The `Windows` part there is a clue—it is a private directory used by the Windows operating system, *not* applications. – Cody Gray - on strike Aug 10 '13 at 16:31
  • 1
    The very first thing you want to do is look at the DirectoryInfo.Attributes property. Never recurse into a directory that has the FileAttributes.System attribute set. Also consider skipping directories that have the Hidden attribute. That Using GetAccessControl() to avoid the exception is possible but is painful, that's code you'd want to google from a reliable source. Like SO, put it in the Search box. – Hans Passant Aug 10 '13 at 17:04
  • I don't know who down-voted the question, seems genuine question to me. – Abhijeet Aug 10 '13 at 18:12

1 Answers1

1

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;
}
Abhijeet
  • 13,562
  • 26
  • 94
  • 175