Check if directory is available in C #?

Possible duplicate:
.NET - check if a directory is accessible without exception handling

I create a small file explorer in Visual Studio 2010 with .NET 3.5 and C #, and I have this function to check if the directory is accessible:

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

But I think that with large directories, it can be slow, trying to get all the subdirectories to check if the directory is accessible. I use this function to prevent errors when trying to examine protected folders or cd / dvd disks without a disk ("Device Error" error).

Is there a better way (faster) to check if the directory is accessible to the application (preferably in NET 3.5)?

+6
source share
2 answers

According to MSDN , Directory.Exists should return false if you do not have read access to the directory. However, you can use Directory.GetAccessControl for this. Example:

 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; } 
+4
source

I think you are looking for the GetAccessControl method, the System.IO.File.GetAccessControl method returns a FileSecurity object that encapsulates the access control for the file.

0
source

Source: https://habr.com/ru/post/921603/


All Articles