ファイル操作

[C#] ファイルの属性を設定する

ファイルの属性を設定するサンプルです。

File.SetAttributes()を使用するパターンと
FileInfoクラスを使用するパターンの2種類あります。

サンプル(File.SetAttributesを使うパターン)

例1)ファイルに読取り専用属性を設定する


using System.IO;

// 対象ファイルパス
string path = @"C:\sample.txt";

// 属性を取得する
FileAttributes fa = File.GetAttributes(path);

// 既存の属性に読取り専用属性を追加する
File.SetAttributes(path, fa | FileAttributes.ReadOnly);

例2)ファイルの読取り専用属性を削除する


using System.IO;

// 対象ファイルパス
string path = @"C:\sample.txt";

// 属性を取得する
FileAttributes fa = File.GetAttributes(path);

// 既存の属性から読取り専用属性を削除する
File.SetAttributes(path, fa & ~FileAttributes.ReadOnly);

サンプル(FileInfoクラスを使用するパターン)

例3)ファイルに読取り専用属性を設定する


using System.IO;

// FileInfoオブジェクトを生成する
FileInfo fi = new FileInfo(@"C:\sample.txt");

// 読取り専用属性を追加する
fi.Attributes |= FileAttributes.ReadOnly;

例4)ファイルの読取り専用属性を削除する


using System.IO;

// FileInfoオブジェクトを生成する
FileInfo fi = new FileInfo(@"C:\sample.txt");

// 読取り専用属性を削除する
fi.Attributes &= ~FileAttributes.ReadOnly;

ファイル属性の種類

ファイル属性値には以下のようなものがあります。

【System.IO.FileAttributes】
意味
ReadOnly 読取り専用ファイル
Hidden 隠しファイル
Normal 通常ファイル
Directory ディレクトリー(フォルダー)
Compressed 圧縮ファイル
Archive アーカイブ状態ファイル
Offline オフライン状態ファイル
System システムファイル(OSが使用するファイル)
SparseFile スパースファイル
Encrypted 暗号化状態ファイル
Temporary 一時ファイル

備考

  • File.SetAttributesの引数に実在しないパスを渡すとSystem.IO.FileNotFoundExceptionが発生します。
  • 引数に渡すパスは、ファイル存在チェックを行った後に渡すようにすると安全です。
    (参考)→ [C#] ファイルの存在チェックを行う

関連記事

-ファイル操作
-