1

如果我有权访问指定目录以列出顶级目录文件,例如系统目录或系统卷信息文件夹等,我将如何检查 .NET 2.0 C# 中的最佳方式。我的代码现在看起来像这样,但我认为它不是检查它的最佳方法,因为它每次都会产生一个异常,由 check 函数处理并根据它返回结果。

我想使用一个不会引发错误的函数来检查指定目录中是否可以访问列表文件,或者我的代码是否可以改进或优化。如果存在访问权限,我可能必须检查一千个目录。引发一千个异常可能会导致问题,但我不知道。

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

1 回答 1

1

检查权限的最佳方法是尝试访问直接(读/写/列表)并捕获 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;
}
于 2013-08-10T18:10:39.270 回答