ファイルやディレクトリに属性を設定するには、Fileクラスの SetAttributesメソッドを使用します。
SetAttributesメソッドを使用する場合は、第1引数には属性を設定したいファイルやディレクトリのパスを、第2引数には属性(FileAttributes列挙体)を指定します。FileAttributes列挙体については前回の記事を参照ください。
下記は指定したファイルが指定したファイルを読み取り専用にする例です。
VBの例
Dim targetFile As String = "C:\Work\Test.txt" '対象ファイル
Dim attr As IO.FileAttributes
'現在の属性を取得する
attr = IO.File.GetAttributes(targetFile)
If (attr And IO.FileAttributes.ReadOnly) = IO.FileAttributes.ReadOnly Then
MessageBox.Show("このファイルは既に読み取り専用ファイルです")
Else
Dim newAttr As FileAttribute
'現在の属性に読み取り専用属性をプラスする
newAttr = attr Or IO.FileAttributes.ReadOnly
IO.File.SetAttributes(targetFile, newAttr)
MessageBox.Show("読み取り専用に設定しました")
End If
C#の例
string targetFile = @"C:\Work\Test.txt"; // 対象ファイル
System.IO.FileAttributes attr;
// 現在の属性を取得する
attr = System.IO.File.GetAttributes(targetFile);
if ((attr & System.IO.FileAttributes.ReadOnly) ==
System.IO.FileAttributes.ReadOnly)
MessageBox.Show("このファイルは既に読み取り専用ファイルです");
else
{
System.IO.FileAttributes newAttr;
// 現在の属性に読み取り専用属性をプラスする
newAttr = attr | System.IO.FileAttributes.ReadOnly;
System.IO.File.SetAttributes(targetFile, newAttr);
MessageBox.Show("読み取り専用に設定しました");
}
Please follow and like us:

コメント