use*_*284 10 c# getdirectories directoryinfo visual-studio-2010
可能重复:
.NET - 检查目录是否可访问而不进行异常处理
我使用.NET 3.5和C#在Visual Studio 2010中制作一个小文件浏览器,我有这个功能来检查目录是否可访问:
RealPath=@"c:\System Volume Information";
public bool IsAccessible()
{
//get directory info
DirectoryInfo realpath = new DirectoryInfo(RealPath);
try
{
//if GetDirectories works then is accessible
realpath.GetDirectories();
return true;
}
catch (Exception)
{
//if exception is not accesible
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但我认为对于大目录,尝试让所有子目录检查目录是否可访问可能会很慢.我在尝试探索受保护的文件夹或没有光盘的cd/dvd驱动器时使用此功能来防止错误("设备未就绪"错误).
是否有更好的方法(更快)检查应用程序是否可以访问目录(最好是在NET 3.5中)?
Chi*_*ata 10
根据MSDN,Directory.Exists
如果您没有对目录的读访问权,则应返回false.但是,您可以使用Directory.GetAccessControl
此功能.例:
public static bool CanRead(string path)
{
var readAllow = false;
var readDeny = false;
var accessControlList = Directory.GetAccessControl(path);
if(accessControlList == null)
return false;
var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
if(accessRules ==null)
return false;
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Read & rule.FileSystemRights) != FileSystemRights.Read) continue;
if (rule.AccessControlType == AccessControlType.Allow)
readAllow = true;
else if (rule.AccessControlType == AccessControlType.Deny)
readDeny = true;
}
return readAllow && !readDeny;
}
Run Code Online (Sandbox Code Playgroud)