How to check if the current user has rights to read a file in .NET

I could not find any function in .NET that just straight out does this.  Furthermore I could not find any code on the web that explained what would be the best way to go about it.  Finally I found some code here:

(post is no longer there)

that checks if you could write to a file and I modified it to check if you could read:

    Public Shared Function CanReadFile(ByVal fileNameWithPath As String) As Boolean
        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 = System.IO.File.GetAccessControl(fileNameWithPath).GetAccessRules(True, True, GetType(System.Security.Principal.SecurityIdentifier)) 
        Dim denyread As Boolean = False
        Dim allowread As Boolean = False
        For Each currentRule As System.Security.AccessControl.FileSystemAccessRule In acl
            If currentUser.User.Equals(currentRule.IdentityReference) Or currentPrinciple.IsInRole(currentRule.IdentityReference) Then
                If currentRule.FileSystemRights = System.Security.AccessControl.FileSystemRights.Read Then
                    If currentRule.AccessControlType.Equals(System.Security.AccessControl.AccessControlType.Deny) Then
                        denyread = True 
                    ElseIf currentRule.AccessControlType.Equals(AccessControlType.Allow) Then
                        allowread = True 
                    End If 
                End If 
            End If 
        Next 
        If allowread And Not (denyread) Then
            Return True 
        Else 
            Return False 
        End If 
    End Function 

Comments

Popular posts from this blog

Show/Hide formatting text in MS Word 2010

Microsoft.ApplicationBlocks. ExceptionManagement The event source x does not exist error

ASP.NET 2.0 DropDownList EnableViewState