ファイル操作
- ファイルを読み書きする方法を紹介
- ファイル操作に関連して@やusingの使い方を紹介
- ファイル操作関連のメソッドを紹介
目次
簡単なファイルの読み書き
プログラムでよく出てくる処理にファイル操作があります。
このページでは、ファイル操作に関連する処理をご紹介します。
まずは1行で書ける簡単なファイルの読み書きの方法からです。
簡単にファイル書込みをする(上書き)
ファイル書込みをする方法から紹介します。
次のサンプルでは、ファイルがなければ新規作成、ファイルがあれば上書きします。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string message = System.DateTime.Now.ToString() + " あいうえお";
// ファイル出力
System.IO.File.WriteAllText(filename, message);
System.Console.WriteLine(filename+"を出力しました");
System.Console.ReadKey(); // キー入力待ち
}
}
C:\temp\test.txtを出力しました
サンプルプログラムの実行方法はトップページを参照してください。
フォルダ「C:\temp」を作成してから実行してください。
「C:\temp」の下にファイル「test.txt」が作成されて、日時と" あいうえお"の文言が出力されます。
すでにファイルがある場合は更新されます。
上記の場合、文字コードはUTF-8BOM無しという形式で保存されます。
文字化け防止のため、文字コードを指定して保存するのが一般的です。
下記は、Shit-JISで保存するプログラムです。
実行結果は同じで、保存されるファイルの文字コードだけが変わります。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string message = System.DateTime.Now.ToString() + " あいうえお";
// ファイル出力
System.IO.File.WriteAllText(filename, message,
System.Text.Encoding.GetEncoding("shift-jis"));
System.Console.WriteLine(filename+"を出力しました");
System.Console.ReadKey(); // キー入力待ち
}
}
ファイル名に@を付ける理由
前述のサンプルでは、ファイル名の指定で@を付けています。
string filename = @"C:\temp\test.txt";
@を付けると、続く文字列は「\マークを特殊殊文字として扱いません」という意味になります。
C#は\マークがエスケープ文字となっていて、特殊文字を使用するために使います。
例えば、"\'"でシングルクォーテーション、"\n"を改行として扱います。
このような特殊文字とせずに\マークはそのまま\マークをして扱うという意味です。
@を付けない場合は\マークを二つ連続して\\と記載する必要があります。
簡単にファイル書込みをする(追記)
文字を上書きせずに追記していくには、System.IO.File.AppendAllTextを使用します。
ファイルがなければ新規作成、ファイルがあれば追記します。
System.Environment.NewLineは、改行を表します。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string message = System.DateTime.Now.ToString() + " あいうえお";
// ファイル出力
System.IO.File.AppendAllText(filename, message + System.Environment.NewLine,
System.Text.Encoding.GetEncoding("shift-jis"));
System.Console.WriteLine(filename+"を出力しました");
System.Console.ReadKey(); // キー入力待ち
}
}
C:\temp\test.txtを出力しました
簡単にファイルから読込みをする
簡単なファイル読込みの方法を紹介します。
System.IO.File.ReadAllTextを使用します。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string message = System.DateTime.Now.ToString() + " あいうえお";
// ファイル出力
System.IO.File.AppendAllText(filename, message + System.Environment.NewLine,
System.Text.Encoding.GetEncoding("shift-jis"));
// ファイル読込み
string readText = System.IO.File.ReadAllText(filename,
System.Text.Encoding.GetEncoding("shift-jis"));
System.Console.WriteLine(readText);
System.Console.ReadKey(); // キー入力待ち
}
}
C2024/04/17 11:05:22 あいうえお
2024/04/17 11:05:25 あいうえお
※実行するごとに行が増えていきます
ファイルを開いて操作する
ファイルを開いて操作する方法を紹介します。
今回は読み書きの方法のみの紹介しますが、StreamWriterやStreamReaderを使うことでファイルの途中の編集など柔軟な処理が行えます。
大きなファイルを操作する場合、この方法を使用しないと処理に時間が掛かる場合があります。
ファイルを開いて書込みをする
StreamWriterでファイルを開いて追記していく方法を紹介します。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string[] strList = new string[] {
"1行目",
"2行目",
"3行目",
"4行目",
"5行目"};
// ファイルを開く、第2引数がtrueの場合は追記、falseの場合は上書き
System.IO.StreamWriter file = new System.IO.StreamWriter(filename, false,
System.Text.Encoding.GetEncoding("shift-jis"));
// 1行ずつ書込み
foreach (string s in strList)
{
file.WriteLine(s);
}
// ファイルクローズ
file.Close();
// ファイル読込み
string readText = System.IO.File.ReadAllText(filename,
System.Text.Encoding.GetEncoding("shift-jis"));
System.Console.WriteLine(readText);
System.Console.ReadKey(); // キー入力待ち
}
}
1行目
2行目
3行目
4行目
5行目
usingステートメントを使う
StreamWriterを使用すると、ファイルを開いて閉じるという処理まで記載する必要があります。
ファイルを確実に閉じる方法としてusingを使用する方法があります。
usingの後に()括りでファイルを開く処理を記載、そのあとの{}括りの処理が終わったら、勝手に終了処理をしてくれる記載方法です。
ファイルを閉じる処理の抜けがなくなるため、こちらを積極的に使いましょう。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
string[] strList = new string[] {
"1行目",
"2行目",
"3行目",
"4行目",
"5行目"};
// ファイルを開く、第2引数がtrueの場合は追記、falseの場合は上書き
using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename, false,
System.Text.Encoding.GetEncoding("shift-jis")))
{
// 1行ずつ書込み
foreach (string s in strList)
{
file.WriteLine(s);
}
}
// ファイル読込み
string readText = System.IO.File.ReadAllText(filename,
System.Text.Encoding.GetEncoding("shift-jis"));
System.Console.WriteLine(readText);
System.Console.ReadKey(); // キー入力待ち
}
}
1行目
2行目
3行目
4行目
5行目
ファイルを開いて読込みをする
StreamReaderを使用したファイル読込みの方法を紹介します。
usingを使用したサンプルを紹介します。
usingを使わない場合は、}のところでfile.Close();を行います。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
// ファイルを開く
using (System.IO.StreamReader file = new System.IO.StreamReader(filename,
System.Text.Encoding.GetEncoding("shift-jis")))
{
// ファイルを読み込む
string text = file.ReadToEnd();
System.Console.WriteLine(text);
}
System.Console.ReadKey(); // キー入力待ち
}
}
1行目
2行目
3行目
4行目
5行目
ファイルを開いて1行ずつ読込みをする
1行ずつファイル読込みする場合は次のように記載します。
StreamReaderのEndOfStreamをチェックしてfalseの間(ファイルの終わりではない間)、ReadLineで1行ずつ読み込みます。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
// ファイルを開く
using (System.IO.StreamReader file = new System.IO.StreamReader(filename,
System.Text.Encoding.GetEncoding("shift-jis")))
{
// ファイルの終わりまで読み込む
while (!file.EndOfStream)
{
string line = file.ReadLine();
System.Console.WriteLine(line);
}
}
System.Console.ReadKey(); // キー入力待ち
}
}
1行目
2行目
3行目
4行目
5行目
その他ファイル操作関連のメソッド
その他のファイル操作関連の処理を紹介します。
まずはサンプルプログラムを見てみましょう。
class Program
{
static void Main()
{
string filename = @"C:\temp\test.txt";
// パスを取得
string filepath = System.IO.Path.GetDirectoryName(filename);
System.Console.WriteLine("ファイルパス:" + filepath);
// ファイル名のみ取得
System.Console.WriteLine("ファイル名:" + System.IO.Path.GetFileName(filename));
// 拡張子なしでファイル名を取得
System.Console.WriteLine("拡張子なしファイル名:" + System.IO.Path.GetFileNameWithoutExtension(filename));
// 拡張子を取得
System.Console.WriteLine("拡張子:" + System.IO.Path.GetExtension(filename));
// 親フォルダを取得
System.Console.WriteLine("親フォルダ:" + System.IO.Directory.GetParent(filepath));
// ファイルの存在チェック
if (System.IO.File.Exists(filename))
{
System.Console.WriteLine(filename+"が見つかりました");
} else {
System.Console.WriteLine(filename+"が見つかりません");
}
// ファイル削除
System.IO.File.Delete(filename);
// ファイル作成(Closeが必要)、FileStreamはバイト配列(バイナリ)で読み書きができる
System.IO.FileStream fs = System.IO.File.Create(filename);
fs.Close();
// System.IO.File.Create(filename).Close(); でも可
string rename_filename = @"C:\temp\test_rename.txt";
// 移動先のファイルがある場合は削除しておく
if (System.IO.File.Exists(rename_filename)) System.IO.File.Delete(rename_filename);
// ファイル移動(同フォルダ内で移動することでファイル名変更)
System.IO.File.Move(filename, rename_filename);
string copy_filename = @"C:\temp\test_copy.txt";
// コピー先のファイルがある場合は削除しておく
if (System.IO.File.Exists(copy_filename)) System.IO.File.Delete(copy_filename);
// ファイルコピー
System.IO.File.Copy(rename_filename, copy_filename);
// フォルダ作成
string testfolder=filepath+@"\testfolder";
System.IO.Directory.CreateDirectory(testfolder);
// フォルダの存在チェック
if (System.IO.Directory.Exists(testfolder))
{
System.Console.WriteLine(testfolder+"が見つかりました");
} else {
System.Console.WriteLine(testfolder+"が見つかりません");
}
// フォルダ削除
System.IO.Directory.Delete(testfolder);
System.Console.ReadKey(); // キー入力待ち
}
}
ファイルパス:C:\temp
ファイル名:test.txt
拡張子なしファイル名:test
拡張子:.txt
親フォルダ:C:\
C:\temp\test.txtが見つかりました
C:\temp\testfolderが見つかりました
ファイル名に関するメソッドには、次のようなものがあります。
| メソッド | 内容 |
|---|---|
| System.IO.Path.GetDirectoryName(ファイル名) | パスを取得 |
| System.IO.Path.GetFileName(ファイル名) | パスを除きファイル名のみを取得 |
| System.IO.Path.GetFileNameWithoutExtension(ファイル名) | 拡張子なしでファイル名を取得 |
| System.IO.Path.GetExtension(ファイル名) | 拡張子を取得 |
| System.IO.Directory.GetParent(フォルダパス) | 親フォルダのパスを取得 |
ファイル操作に関するメソッドには、次のようなものがあります。
| メソッド | 内容 |
|---|---|
| System.IO.File.Exists(ファイル名) | ファイルの存在チェック |
| System.IO.File.Create(ファイル名).Close() | ファイルを作成 |
| System.IO.File.Delete(ファイル名) | ファイルを削除 |
| System.IO.File.Move(移動元ファイル名, 移動先ファイル名) | ファイルを移動(同フォルダ内にすることでファイル名変更) |
| System.IO.File.Copy(コピー元ファイル名, コピー先ファイル名) | ファイルをコピー |
フォルダ操作に関するメソッドには、次のようなものがあります。
| メソッド | 内容 |
|---|---|
| System.IO.Directory.Exists(フォルダ名) | フォルダの存在チェック |
| System.IO.Directory.CreateDirectory(フォルダ名) | フォルダを作成 |
| System.IO.Directory.Delete(フォルダ名) | フォルダを削除 |
| System.IO.Directory.Move(移動元フォルダ名, 移動先フォルダ名) | フォルダを移動(同フォルダ内にすることでフォルダ名変更) |
フォルダのコピーのメソッドはありません。
フォルダをコピーする場合は、フォルダを作成して、子ファイルを個別にコピーする必要があります。