LoginSignup
0
0

C#で一時的にファイルを作成して編集、その後削除する

Last updated at Posted at 2023-11-07

経緯

一時的にCSVファイルを作成し、外部に送信した後に削除する機能を作ることになった。
ファイルの作成と編集が別々に書いてある記事が多かったが、作成してそのまま編集できる方法があるようなので、備忘録代わりに。

環境

言語:C#
バージョン:.NET Framework 4.8

仕様の概要

  1. C#のResourcesフォルダの中にsample.csvを作成
  2. 中身のデータを書き加えていく
  3. 外部にファイルを送信する(この記事では中略)
  4. ファイルを削除する

コード

完成形は以下です。
この記事ではFile.CreateTextを使用します。

List<string> values = new List<string>() {
  // ID, 氏名, 誕生日, 性別
  @"""1"",""田中太郎"",""1900/04/01"",""男""",
  @"""2"",""中田花子"",""1900/05/21"",""女""",
  @"""3"",""高橋さとる"",""1900/10/03"",""男""",
}

// 1. C#のResourcesフォルダの中にsample.csvを作成
string filePath = "~/Resources/sample.csv";
string physicalPath = HostingEnvironment.MapPath(@filePath);

// 2. 中身のデータを書き加えていく
using (StreamWriter sw = File.CreateText(physicalPath)) {
  foreach (string item in values) {
    sw.WriteLine(item);
  }
}

// 3. 外部にファイルを送信する(この記事では中略)

// 4. ファイルを削除する
File.Delete(physicalPath);

続いて簡単に解説していきます。

// 1. C#のResourcesフォルダの中にsample.csvを作成
string filePath = "~/Resources/sample.csv";
string physicalPath = HostingEnvironment.MapPath(@filePath);

ここで、どこにどんな名前でファイルを作るかを指定しています。
HostingEnvironment.MapPathを使うことで、サーバー上の物理パスを取得しています。

// 2. 中身のデータを書き加えていく
using (StreamWriter sw = File.CreateText(physicalPath)) {
  foreach (string item in values) {
    sw.WriteLine(item);
  }
}

File.CreateTextでファイルを作成しています。同じ名前のファイルがあった場合は上書きされます。
その後、StreamWriter.WriteLineを使って一行ずつデータを書き込んでいます。

// 4. ファイルを削除する
File.Delete(physicalPath);

そのまんまですが、先ほど作成したsample.csvファイルを削除しています。
ファイルが見つからない場合でも、特にエラーは起きませんでした。

その他

文字エンコーディングを指定する方法についても記事にしました。

参考

0
0
0

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
0
0