0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#で一時的にファイルを作成して編集、その後削除する【文字エンコーディング指定あり】

0
Last updated at Posted at 2023-11-21

経緯

以前、以下の記事でCSVファイル作成処理を紹介したのですが、動作確認を進めたところ、日本語を入力したCSVファイルをExcelアプリで開くと文字化けしました、、

そのため、文字エンコーディングの指定をしつつ、ファイルを作成して編集する方法を、備忘録がてら記事にしておこうと思います。

環境

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

仕様の概要

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

コード

完成形は以下です。
今回使うのはStreamWriterです。

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 = new StreamWriter(physicalPath, false, System.Text.Encoding.UTF8))
{
    foreach (string item in values)
    {
        sw.WriteLine(item);
    }
}

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

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

StreamWriterを使っている部分以外は以前の記事と変わりないため、その説明は割愛します。

StreamWriter(physicalPath, false, System.Text.Encoding.UTF8)について、
第一引数にファイルの物理パスを渡しています。
第二引数ではfalseを指定して、同じ名前のファイルが見つかった場合は上書きをするようにしています。
第三引数では文字エンコーディングの指定をしています。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?