[C#]StreamWriterクラスを使用して文字コードを指定してファイルに書き込む
第3引数にEncodingクラスのGetEncoding メソッドを使用してコードページを指定する。以下は四通りの方法でそれぞれ文字列をファイルに書き出した例。
OutVar.cs
using System.IO;
using System.Text;
using (var sw = new StreamWriter("result/out_default.txt", false)) {
sw.WriteLine("メイショウドトウ役の和多田美咲さん");
}
Encoding enc;
enc = Encoding.GetEncoding("shift_jis");
using (var sw = new StreamWriter("result/out_sjis.txt", false, enc)) {
sw.WriteLine("メイショウドトウ役の和多田美咲さん");
}
enc = Encoding.GetEncoding("utf-8");
using (var sw = new StreamWriter("result/out_utf8.txt", false, enc)) {
sw.WriteLine("メイショウドトウ役の和多田美咲さん");
}
enc = new UTF8Encoding();
using (var sw = new StreamWriter("result/out_utf8encoding.txt", false, enc)) {
sw.WriteLine("メイショウドトウ役の和多田美咲さん");
}
実行してみる。
>OutVar.exe
>type result\out_sjis.txt
メイショウドトウ役の和多田美咲さん
>certutil -encodehex -f out_default.txt dump.txt 10 > nul && type dump.txt
0000 e3 83 a1 e3 82 a4 e3 82 b7 e3 83 a7 e3 82 a6 e3
0010 83 89 e3 83 88 e3 82 a6 e5 bd b9 e3 81 ae e5 92
0020 8c e5 a4 9a e7 94 b0 e7 be 8e e5 92 b2 e3 81 95
0030 e3 82 93 0d 0a
>certutil -encodehex -f out_sjis.txt dump.txt 10 > nul && type dump.txt
0000 83 81 83 43 83 56 83 87 83 45 83 68 83 67 83 45
0010 96 f0 82 cc 98 61 91 bd 93 63 94 fc 8d e7 82 b3
0020 82 f1 0d 0a
>certutil -encodehex -f out_utf8.txt dump.txt 10 > nul && type dump.txt
0000 ef bb bf e3 83 a1 e3 82 a4 e3 82 b7 e3 83 a7 e3
0010 82 a6 e3 83 89 e3 83 88 e3 82 a6 e5 bd b9 e3 81
0020 ae e5 92 8c e5 a4 9a e7 94 b0 e7 be 8e e5 92 b2
0030 e3 81 95 e3 82 93 0d 0a
>certutil -encodehex -f out_utf8encoding.txt dump.txt 10 > nul && type dump.txt
0000 e3 83 a1 e3 82 a4 e3 82 b7 e3 83 a7 e3 82 a6 e3
0010 83 89 e3 83 88 e3 82 a6 e5 bd b9 e3 81 ae e5 92
0020 8c e5 a4 9a e7 94 b0 e7 be 8e e5 92 b2 e3 81 95
0030 e3 82 93 0d 0a
以上より、StreamWriterクラスの第3引数の指定と書き出されるファイルの文字コードの関係は、以下であることがわかる。
文字コードを未指定 → UTF-8(BOM付き)
Shift_JIS → Shift_JIS
UTF-8 → UTF-8(BOM無し)
UTF8Encodingクラスをそのまま指定 → UTF-8(BOM付き)
« [R]二つのtibbleを一つに結合(左外部結合)する | トップページ | [C#]エラー「CS8370 機能 'target-typed オブジェクトの作成' は C# 7.3 では使用できません。9.0 以上の言語バージョンをお使いください。」 »
「C#」カテゴリの記事
- [C#]リストの要素を削除する(2024.05.02)
- [C#]リストに要素を追加する(2024.03.10)
- [C#]リストを作成する(2024.03.09)
- [C#]エラー「CS8370 機能 'target-typed オブジェクトの作成' は C# 7.3 では使用できません。9.0 以上の言語バージョンをお使いください。」(2024.03.08)
- [C#]StreamWriterクラスを使用して文字コードを指定してファイルに書き込む(2024.03.07)
« [R]二つのtibbleを一つに結合(左外部結合)する | トップページ | [C#]エラー「CS8370 機能 'target-typed オブジェクトの作成' は C# 7.3 では使用できません。9.0 以上の言語バージョンをお使いください。」 »

コメント