C#/VB ファイルの属性を取得・設定する

ファイルの属性を取得・設定するにはどうしたらいいですか?

ファイルの属性はGetAttributesで取得、SetAttributesで設定できます。

目次

ファイルの属性を取得する

 FileクラスのGetAttributesメソッドを利用すことで、ファイルの属性を取得することができます。
引数には、対象とするファイルパスを指定します。

System.IO.File.GetAttributes(ファイルパス)

  戻り値は、FileAttributes列挙体を返します。FileAttributesの主要な値は以下の通りです。

メンバー値説明
Archiveファイルのアーカイブの状態
Compressed圧縮ファイル
Directoryディレクトリ
Hidden隠しファイル
Normal通常ファイル
ReadOnly読み取り専用ファイル
Systemシステムファイル
Temporary一時ファイル
主に使うFileAttributesのメンバー値

その他のメンバーに関してはMSDNのFileAttributes解説よりご確認下さい。

string strName = @"C:\debug1\test1\test1.txt";
var ret = System.IO.File.GetAttributes(strName);

if ((ret & System.IO.FileAttributes.System) != 0)
{
    Debug.WriteLine("システムファイル");
}
if ((ret & System.IO.FileAttributes.ReadOnly) != 0)
{
    Debug.WriteLine("読み取り専用ファイル");
}
if ((ret & System.IO.FileAttributes.Compressed) != 0)
{
    Debug.WriteLine("圧縮ファイル");
}
if ((ret & System.IO.FileAttributes.Hidden) != 0)
{
    Debug.WriteLine("隠しファイル");
}
  
Dim strName As String = "C:\debug1\test1\test1.txt"
Dim ret = System.IO.File.GetAttributes(strName)

If (ret And System.IO.FileAttributes.System) <> 0 Then
	Debug.WriteLine("システムファイル")
End If
If (ret And System.IO.FileAttributes.[ReadOnly]) <> 0 Then
	Debug.WriteLine("読み取り専用ファイル")
End If
If (ret And System.IO.FileAttributes.Compressed) <> 0 Then
	Debug.WriteLine("圧縮ファイル")
End If
If (ret And System.IO.FileAttributes.Hidden) <> 0 Then
	Debug.WriteLine("隠しファイル")
End If     
CHECK

ファイルには複数の属性がついている可能性があり、GetAttributesの返り値はビットごとの組み合わせになります。

ファイルの属性を設定する

FileクラスのSetAttributesメソッドを利用することで、ファイルに属性を設定することができます。
SetAttributesメソッドの引数には、対象とするファイルのパスと属性を指定します。

System.IO.File.SetAttributes(ファイルパス, 属性)

属性は、FileAttributes列挙体(上記参照)の値で指定します。

string strName = @"C:\debug1\test1\test1.txt";
System.IO.File.SetAttributes(strName,System.IO.FileAttributes.ReadOnly);
Dim strName As String = "C:\debug1\test1\test1.txt"
System.IO.File.SetAttributes(strName, System.IO.FileAttributes.[ReadOnly])

リスキリングでキャリアアップしてみませんか?

リスキリング(学び直し)は、経済産業省が推奨しており、

今だけ、最大70%のキャッシュバックを受けることができます。

リスキリング 給付金が出るスクール紹介

最大70%の給付金が出るおすすめのプログラミングスクール!

国策で予算が決められているため申し込みが多い場合は早期に終了する可能性があります!

興味のある方はすぐに確認しましょう。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする

CAPTCHA


目次