Is my file writable?

Trying to open the file inside a Try...Catch block is a bad idea.  Try...Catch structures are expensive.

Private Function FileIsNotLocked(ByVal fullPathToFile As String) As Boolean
        Dim blnReturn As Boolean = True
        Dim fs As System.IO.FileStream

        Try
            fs = System.IO.File.OpenWrite(fullPathToFile)
            fs.Close()
        Catch ex As System.IO.IOException
            blnReturn = False
        End Try

        Return blnReturn
    End Function

Instead, ask the file system directly. (Requires a ‘System.Security’ import.)

Private Function FileIsWritable(filePath As String) As Boolean
        If Not File.Exists(filePath) Then
            Return False
        End If
        Dim permissionSet = New PermissionSet(Permissions.PermissionState.None)
        Dim writePermission = New Permissions.FileIOPermission(Permissions.FileIOPermissionAccess.Write, filePath)
        permissionSet.AddPermission(writePermission)
        Return (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
    End Function

Update 3/13/16: Try...Catch blocks aren’t nearly as expensive now as they were back in .NET 1.0, but it’s still a good idea to proactively interrogate the file for its security.

Advertisements