1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| Imports System.Security.Principal
Imports System.Security.AccessControl
Public Shared Class FileHelper
Public Shared Function HasPermissionOnDirectory(ByVal path As String, ByVal permission As FileSystemRights) As Boolean
Return HasPermission(path, permission, Directory.GetAccessControl)
End Function
Public Shared Function HasPermissionOnFile(ByVal path As String, ByVal permission As FileSystemRights) As Boolean
Return HasPermission(path, permission, File.GetAccessControl)
End Function
Private Shared Function HasPermission(ByVal path As String, ByVal permission As FileSystemRights, ByVal fileSecurityFactory As Func(Of String, FileSystemSecurity)) As Boolean
Try
Dim allow As var = False
Dim deny As var = False
Dim accessControlList As var = fileSecurityFactory(path)
Dim accessRules As var = accessControlList.GetAccessRules(True, True, GetType(SecurityIdentifier))
For Each rule As FileSystemAccessRule In accessRules
If (permission And rule.FileSystemRights) <> permission Then
Continue
End If
If rule.AccessControlType = AccessControlType.Allow Then
allow = True
ElseIf rule.AccessControlType = AccessControlType.Deny Then
deny = True
End If
Next
Return allow AndAlso Not deny
Catch generatedExceptionName As UnauthorizedAccessException
Return False
End Try
End Function
End Class |
Partager