準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
using System.Text;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (var sw = new StreamWriter(@"F:\test1.txt", false, new UTF8Encoding(true)))
{
sw.WriteLine("東京都新宿区");
}
}
}
}
解説
System.Text 名前空間の UTF8Encoding クラスを使用すると、BOM の有無を指定できます。
F ドライブのルートに test.txt が作成されます。このファイルをバイナリエディタで参照すると、ファイルの先頭に EF BB EF が付いていることが分かります。
結果

動作確認環境
Visual Studio 2022 Professional (.NET 7 C#11)
ログ
初版:2016.04.30 Visual Studio 2015 Professional (C# 6.0)