ファイルの属性を取得するには、FileクラスのGetAttributesメソッドを使用します。
GetAttributesの引数には、属性を調べたいファイルのパスを指定します。このメソッドはFileクラスのメンバですがディレクトリの属性も調べることができます。
GetAttributesメソッドの戻り値は、FileAttributes型となっており、特定のビットに属性情報がセットされます。
したがって、どのような属性を持っているかを調べるには、GetAttributesメソッドの戻り値とFileAttributes列挙体(下記)の値でビット演算を行う必要があります。
| メンバ名 | 説明 |
|---|---|
| ReadOnly | 読み取り専用 |
| Hidden | 隠し属性 |
| System | システムファイル |
| Directory | ディレクトリ |
| Archive | アーカイブ |
| Device | 今後使用するために予約されている |
| Normal | 標準のファイル |
| temporary | 一時ファイル |
| SparseFile | スパースファイル |
| ReparsePoint | リパースポイントが含まれている |
| Compressed | 圧縮ファイル |
| Offline | ファイルはオフラインである |
| NotContentIndex | インデックス付けサービスによるインデックスが付いていない |
| Encrypted | ファイルまたはディレクトリは暗号化されている |
下記は、指定したファイルが読み取り専用かどうかを調べる例です。
VBの例
<br />Dim targetFile As String = "C:\Work\Test.txt" '対象ファイル<br />Dim attr As IO.FileAttributes<br /><br />'属性を取得する<br />attr = IO.File.GetAttributes(targetFile)<br /><br />If (attr And IO.FileAttributes.ReadOnly) = IO.FileAttributes.ReadOnly Then<br /> MessageBox.Show("読み取り専用ファイルです")<br />Else<br /> MessageBox.Show("読み取り専用ファイルではありません")<br />End If<br />
C#の例
<br />string targetFile = @"C:\Work\Test.txt"; // 対象ファイル<br />System.IO.FileAttributes attr;<br /><br />// 属性を取得する<br />attr = System.IO.File.GetAttributes(targetFile);<br /><br />if ((attr & System.IO.FileAttributes.ReadOnly) ==<br /> System.IO.FileAttributes.ReadOnly)<br /> MessageBox.Show("読み取り専用ファイルです");<br />else<br /> MessageBox.Show("読み取り専用ファイルではありません");<br />
Please follow and like us:

コメント
[…] HIRO’s.NET の紹介 « [Tips][ファイル操作] ファイル属性を取得する […]