TheSwamp
Code Red => .NET => Topic started by: Jeff H on November 16, 2011, 08:37:23 AM
-
Does anyone know a better a way or less klunky than DirectorySecurity to check if you have access to a directory?
Here
foreach (string directory in Directory.GetDirectories(directoryPath))
{
try
{
Directory.GetDirectories(directory);
///////Do your thing;
///////Like add directory as a node to a TreeView if GetDirectories does not
///////throw a exception
}
catch (UnauthorizedAccessException uex)
{
}
}
I guess it is because it can change from the time you checked.
-
I found some VB code:
Public Function CanWriteTo(ByVal DirectoryPath As String) As Boolean
Dim dirInfo As System.IO.DirectoryInfo = FileIO.FileSystem.GetDirectoryInfo(DirectoryPath)
Dim currentUser As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim currentPrinciple As System.Security.Principal.WindowsPrincipal = System.Threading.Thread.CurrentPrincipal
Dim acl As System.Security.AccessControl.AuthorizationRuleCollection = dirInfo.GetAccessControl().GetAccessRules(True, True, GetType(System.Security.Principal.SecurityIdentifier))
Dim currentRule As System.Security.AccessControl.FileSystemAccessRule
Dim denyread As Boolean = False
Dim allowread As Boolean = False
For x As Integer = 0 To acl.Count - 1
currentRule = acl(x)
If currentUser.User.Equals(currentRule.IdentityReference) Or currentPrinciple.IsInRole(currentRule.IdentityReference) Then
If currentRule.AccessControlType.Equals(Security.AccessControl.AccessControlType.Deny) Then
If (currentRule.FileSystemRights And Security.AccessControl.FileSystemRights.Write) = Security.AccessControl.FileSystemRights.Write Then denyread = True
Else
If currentRule.AccessControlType.Equals(AccessControlType.Allow) Then allowread = True
End If
End If
Next
If allowread And Not (denyread) Then
Return True
Else
Return False
End If
End Function
-
Thanks Huiz