c#逐行读取文件
File reading line by line in c#
我正在从文本文件 input.txt 中读取 2 个输入。我有文本文件
12#15#
17#71#
18#15#
我使用过这种语法,但它读取最后一行 only.why 它不起作用?读取 line bye line 的最佳循环条件可能是 12+15 并显示 27 并读取下一行 17+71 并显示 88 并处理 last
StreamReader reader = new StreamReader("input.txt");
string line;
int count = 0;
while ((line = reader.ReadLine()) != null)
{
string[] splitted = line.Split('#');
string first = splitted[0].Trim();
string second = splitted[1].Trim();
x = Convert.ToInt32(first);
y = Convert.ToInt32(second);
一般回答
您应该附加到文本框,但在每次循环迭代中都会覆盖它。
我建议将 txtSum.Text 赋值移到循环之外,只运行一次,因为 txtSum.set_Text 是涉及图形重绘的操作,而且开销很大。
示例
try
{
StreamReader reader = new StreamReader("input.txt");
string line;
StringBuilder sum = new StringBuilder();
int count = 0;
while ((line = reader.ReadLine()) != null)
{
string[] splitted = line.Split('#');
string first = splitted[0].Trim();
string second = splitted[1].Trim();
sum.Append(first).Append(second);
}
txtSum.Text = sum.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
我正在从文本文件 input.txt 中读取 2 个输入。我有文本文件
12#15#
17#71#
18#15#
我使用过这种语法,但它读取最后一行 only.why 它不起作用?读取 line bye line 的最佳循环条件可能是 12+15 并显示 27 并读取下一行 17+71 并显示 88 并处理 last
StreamReader reader = new StreamReader("input.txt");
string line;
int count = 0;
while ((line = reader.ReadLine()) != null)
{
string[] splitted = line.Split('#');
string first = splitted[0].Trim();
string second = splitted[1].Trim();
x = Convert.ToInt32(first);
y = Convert.ToInt32(second);
一般回答 您应该附加到文本框,但在每次循环迭代中都会覆盖它。
我建议将 txtSum.Text 赋值移到循环之外,只运行一次,因为 txtSum.set_Text 是涉及图形重绘的操作,而且开销很大。
示例
try
{
StreamReader reader = new StreamReader("input.txt");
string line;
StringBuilder sum = new StringBuilder();
int count = 0;
while ((line = reader.ReadLine()) != null)
{
string[] splitted = line.Split('#');
string first = splitted[0].Trim();
string second = splitted[1].Trim();
sum.Append(first).Append(second);
}
txtSum.Text = sum.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}