Search code examples
.netvb.netfile-attributessystem.io.fileinfo

FileInfo.IsReadOnly versus FileAttributes.ReadOnly


Is there any difference between these two ways of checking whether a file is read-only?

Dim fi As New FileInfo("myfile.txt")

' getting it from FileInfo
Dim ro As Boolean = fi.IsReadOnly
' getting it from the attributes
Dim ro As Boolean = fi.Attributes.HasFlag(FileAttributes.ReadOnly)

If not why are there two different possibilities?


Solution

  • Well, according to the .NET source code the IsReadOnly property just checks the attributes of the file.

    Here is the particular property:

    public bool IsReadOnly {
      get {
         return (Attributes & FileAttributes.ReadOnly) != 0;
      }
      set {
         if (value)
           Attributes |= FileAttributes.ReadOnly;
         else
           Attributes &= ~FileAttributes.ReadOnly;
         }
    }
    

    This translates to the following VB.Net Code

    Public Property IsReadOnly() As Boolean
        Get
            Return (Attributes And FileAttributes.[ReadOnly]) <> 0
        End Get
        Set
            If value Then
                Attributes = Attributes Or FileAttributes.[ReadOnly]
            Else
                Attributes = Attributes And Not FileAttributes.[ReadOnly]
            End If
        End Set
    End Property
    

    As to why there are multiple methods, this can be seen everywhere. For example, you can use StringBuilder.append("abc" & VbCrLf) or StringBuilder.appendLine("abc")