【C#】ファイルの読み書き
はじめに
ただの簡単なファイルへの書き込み、読み込みのやり方
System.IO.StreamReader, StreamWriterを使う
StreamWriterのコンストラクタの第2引数はtrueで追記、falseで上書き。コンストラクタはいっぱいオーバーロードされてるので詳しくはリファレンスを。
append
Type: System.Boolean
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.
using System.IO; public class Test { static string FILE_NAME = "test.txt"; public static void Main () { using (StreamWriter sw = new StreamWriter(FILE_NAME, false)){ sw.WriteLine("Test"); } if (File.Exists (Application.dataPath + FILE_NAME)) { using (StreamReader sr = File.OpenText (FILE_NAME)) { Console.WriteLine(sr.ReadLine ());//1行 //Console.WriteLine(sr.ReadToEnd ());//全部 } } } }
1行づつ扱いたかったら
while( (line = sr.ReadLine()) != null) { Console.WriteLine(line); }
usingについて
ファイルストリームは開いているときロックされて他からアクセスできないので、閉じる必要がある。基本的に関数の中の変数などが参照されなくなったら自動的にガベージ・コレクションが行われるが、そのタイミングは参照されなくなった時点ではないので、ファイルストリームなどの場合は明示的に解放する必要がある。StreamReaderにはClose()メソッドがあり、使い終わったらClose()すればいいのだが、リソースを解放するためにDispose()というメソッドが実装されている(Close()は破棄するわけではない、詳しく参考を。)。そこで、Dispose()を自動的にやってくれるのがusing構文という訳だ。以下の2つのプログラムは同じことだ。
using (Font font1 = new Font("Arial", 10.0f)) { byte charset = font1.GdiCharSet; }
{ Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } }
参考
using Statement (C# Reference) | Microsoft Docs
StreamWriter コンストラクター (String, Boolean) (System.IO)
.NET TIPS ガベージ・コレクタを明示的に動作させるには? - C# VB.NET - @IT
ファイル操作 - C# によるプログラミング入門 | ++C++; // 未確認飛行 C