Author Topic: Directory Access  (Read 1446 times)

0 Members and 1 Guest are viewing this topic.

Jeff H

  • Needs a day job
  • Posts: 6150
Directory Access
« 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
Code: [Select]
     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.

huiz

  • Swamp Rat
  • Posts: 919
  • Certified Prof C3D
Re: Directory Access
« Reply #1 on: November 16, 2011, 09:57:04 AM »
I found some VB code:

Code: [Select]
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

The conclusion is justified that the initialization of the development of critical subsystem optimizes the probability of success to the development of the technical behavior over a given period.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: Directory Access
« Reply #2 on: November 16, 2011, 11:00:47 AM »
Thanks Huiz