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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s