LoginSignup
3
5

More than 1 year has passed since last update.

C#ファイルIOチートシート

Last updated at Posted at 2022-06-29
using System.IO;

var str = "Hello \n World";
var path = "./a/a.txt";

// 作成
File.Create(path); // 存在すれば上書き(内容消える) フォルダ無いとエラー
Directory.CreateDirectory("./a/b/c/");   //なければ再帰的に作成

// 読込
var t = File.ReadAllText(path);  // 文字列として
var lines = File.ReadAllLines(path);  // 文字列リストとして
foreach(var s in lines){
  //...
}
// streamで (usingで自動クローズ)
using(var f = new StreamReader(path)){
  while(f.ReadLine() is {} s){
      Console.WriteLine(s);
  }
}

// 書き込み(ファイルがなければ作成される)
File.WriteAllText(path, str); // 文字列を
File.WriteAllLines(path, strList); // 文字列リスト・配列を
// streamで (usingで自動クローズ)
using(var f = new StreamWriter(path, false)){// trueで追記(Append)可能
  file.WriteLine(str); //など
}
// ※(いずれも引数でエンコード Encoding.UTF8 等指定可)

// 存在チェック
if(File.Exists(path)) //...
if(Directory.Exists(dir)) //...

以上

3
5
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
3
5