如果目录有权访问列表文件,或者会出现未经授权的访问异常,那么在C#中检查的最佳方法是什么
本文关键字:访问 异常 方法 是什么 最佳 检查 授权 列表 文件 或者 如果 | 更新日期: 2023-09-27 18:27:04
如果我有权访问指定的目录,我将如何在.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;
}
检查权限的最佳方法是尝试访问目录(读/写/列表)&捕获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;
}