what is the best way to check in C# .NET if a dire

2019-10-18 11:20发布

我怎么会以最好的方式为您在.NET 2.0 C#如果我有机会到指定的目录上市顶级目录中的文件,例如一个系统目录或者System Volume Information文件等我的代码,它现在看起来是这样,但我认为这不检查它,因为它会产生一个异常,被单向函数处理并返回基于其结果每次的最佳途径。

我想用它不会引发错误,以检查是否在指定的目录访问列表文件或者也许我的代码可以改进或优化的功能。 我可能有过千名的目录,如果存在一个访问或不检查。 提高千个异常可能导致一个问题,但我不知道。

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

Answer 1:

检查的权限,最好的办法是尝试访问direcoty(读/写/列表)赶上UnauthorizedAccessException。

但是出于某种原因在那里,如果你想查询的权限,下面的代码应满足您的需要。 你需要读Access Rules的目录。

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


文章来源: 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