1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#入門 第9章】ファイル読み書きの基本|テキストを保存・読み込む力を手に入れろ!

Posted at

【C#入門 第9章】ファイル読み書きの基本|テキストを保存・読み込む力を手に入れろ!

こんにちは、 CSharpTimes の一之瀬シィよ💠
今回はアプリに“記憶”を与える超重要機能、 ファイルの読み書き をマスターするわよ!


📂 ファイルを保存するには(書き込み)

StreamWriter を使って保存!

using System.IO;

StreamWriter writer = new StreamWriter("output.txt");
writer.WriteLine("こんにちは、ファイルさん!");
writer.Close();
  • "output.txt":カレントフォルダに作成される
  • WriteLine():1行ずつ書き込み
  • Close():書き込み終了(忘れるとダメよ!)

📥 ファイルを読むには(読み込み)

StreamReader を使って読み込み!

using System.IO;

StreamReader reader = new StreamReader("output.txt");
string text = reader.ReadToEnd();
reader.Close();

Console.WriteLine("読み込んだ内容:" + text);
  • ReadToEnd():ファイル全体を一気に読む
  • ReadLine():1行ずつ読み込むこともできる

✅ usingブロックでラクに書こう

using を使うと Close() を自動でやってくれる!スマートな書き方はこちら👇

using (StreamWriter writer = new StreamWriter("data.txt"))
{
    writer.WriteLine("ラクちん書き込み✨");
}

using (StreamReader reader = new StreamReader("data.txt"))
{
    string line = reader.ReadLine();
    Console.WriteLine("読み込み:" + line);
}

🔐 ちょっとだけ注意点!

  • ファイルが存在しないと StreamReader は例外を出すわよ!
  • 書き込み時は 上書き になるので気をつけて(追記は true 指定)
new StreamWriter("log.txt", true); // ← 追記モード

📌 まとめ

  • StreamWriter で書き込み、StreamReader で読み込み
  • using を使うと自動的に閉じられて安心
  • ファイルがなければ作る、あれば読む、それが基本!

次回は、 「第10章:JSONとXML操作」 よ。
テキストだけじゃ満足できない…そんなあなたに、構造化データとの華麗な戯れを教えてあげるわ💢

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?