[Tips][ファイル操作] ファイル属性を取得する

スポンサーリンク

ファイルの属性を取得するには、FileクラスGetAttributesメソッドを使用します。

GetAttributesの引数には、属性を調べたいファイルのパスを指定します。このメソッドはFileクラスのメンバですがディレクトリの属性も調べることができます。

GetAttributesメソッドの戻り値は、FileAttributes型となっており、特定のビットに属性情報がセットされます。

したがって、どのような属性を持っているかを調べるには、GetAttributesメソッドの戻り値とFileAttributes列挙体(下記)の値でビット演算を行う必要があります。

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 &amp; System.IO.FileAttributes.ReadOnly) ==<br />    System.IO.FileAttributes.ReadOnly)<br />    MessageBox.Show("読み取り専用ファイルです");<br />else<br />    MessageBox.Show("読み取り専用ファイルではありません");<br />
Please follow and like us:

コメント

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

タイトルとURLをコピーしました