準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var sr = new StreamReader(@"D:\test.txt");
string s1 = sr.ReadToEnd();
s1 = s1.Replace(Environment.NewLine, "\r");
s1 = s1.Trim('\r');
string[] s2 = s1.Split('\r');
foreach (string item in s2)
{
listBox1.Items.Add(item);
}
}
}
}
解説
テキストデータを変数 s1 に一度に読み込みます。改行コードで区切りますが、標準では \r\n の 2 文字含まれていますので、\r だけにします。さらに最後の \r は除去します。
そして、\r 文字を基準にテキストデータを分割します。
結果
動作確認環境
Visual Studio 2022 Professional (.NET8 C#12)
ログ
初版:2016.05.11 Visual Studio 2015 Professional (C# 6.0)
