FileInfo.IsReadOnly 对比 FileAttributes.ReadOnly

FileInfo.IsReadOnly versus FileAttributes.ReadOnly

这两种检查文件是否只读的方式有什么区别吗?

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)

如果不是为什么会有两种不同的可能性?

嗯,根据.NET source code IsReadOnly 属性只是检查文件的属性。

这里是特定的 属性:

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

这转化为以下VB.Net代码

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

至于为什么有多种方法,这个随处可见。例如,您可以使用 StringBuilder.append("abc" & VbCrLf)StringBuilder.appendLine("abc")