Checking Permissions Before Accessing A File

Often, it’s a good idea to make sure the user trying to access the file has permissions to it before performing an operation like read, write or delete. Below is code that makes this pretty easy.

  Sub DemandFileReadPermission(ByVal fileName As String)

    If System.IO.File.Exists(fileName) Then

      Dim filePermission As New System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, fileName)

      filePermission.Demand()

    End If

  End Sub

 

  Sub DemandFileWritePermission(ByVal fileName As String)

    If System.IO.File.Exists(fileName) Then

      Dim destinationFilePermission As New System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Write, System.Security.AccessControl.AccessControlActions.Change, fileName)

      destinationFilePermission.Demand()

    End If

  End Sub

One warning though… performing a permission .Demand takes time. In a quick test on my machine it was a pretty consistent 10 milliseconds. So you might not want to do this all of the time.

Tip by: David McCarter