我的 StreamReader 代码只读取每隔一行 c#
这是我解决的程序,它将读取带有分隔符的文本文件并使用 datagridview 将数据传输到表中。
现在我遇到了困难,因为 while 循环只读取每隔一行。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
TextReader tr = new StreamReader("aplusixdata.txt");
string[] columns = {"School","Room No.","Student No.","Excercise No.","Problem No.",
"Nth Problem Taken","Date","Time","Excercise Degree",
"Action No.","Duration","Action","Error","Etape",
"Expression","Etat","Cursor Location","Selection",
"Equivalence","Resolution","Empty"};
while (tr.ReadLine() != null)
{
int i = 0;
char[] delimiterChar = { ';' };
string words = tr.ReadLine();
text = words.Split(delimiterChar);
DataRow row = t.NewRow();
foreach (String data in text)
{
//System.Console.WriteLine(data);
System.Console.WriteLine(i);
row[columns[i]] = data;
i++;
}
t.Rows.Add(row);
}
}
This is my solved program that will read a text file with delimiters and transfer the data to a table using datagridview.
Now I'm having a hard time because the while loop is only reading every other line.
This is my code:
private void Form1_Load(object sender, EventArgs e)
{
TextReader tr = new StreamReader("aplusixdata.txt");
string[] columns = {"School","Room No.","Student No.","Excercise No.","Problem No.",
"Nth Problem Taken","Date","Time","Excercise Degree",
"Action No.","Duration","Action","Error","Etape",
"Expression","Etat","Cursor Location","Selection",
"Equivalence","Resolution","Empty"};
while (tr.ReadLine() != null)
{
int i = 0;
char[] delimiterChar = { ';' };
string words = tr.ReadLine();
text = words.Split(delimiterChar);
DataRow row = t.NewRow();
foreach (String data in text)
{
//System.Console.WriteLine(data);
System.Console.WriteLine(i);
row[columns[i]] = data;
i++;
}
t.Rows.Add(row);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您两次调用
ReadLine
。更好的方法可能是:
while (!tr.EndOfStream)
编辑:最好将代码用
using
子句包围。That is because you are making a call to
ReadLine
twice.A better way could be:
while (!tr.EndOfStream)
EDIT: It will be better to have the code surrounded by
using
clause.您在每次迭代中调用
ReadLine
两次 - 一次在这里:一次在这里:
将其更改为每次迭代仅读取一次:(
请注意,我还提取了
char[ ]
跳出循环 - 实际上没有必要在每次迭代时都这样做。我个人会将其设为私有静态变量。)其他几个风格点:
text
变量?为什么不在循环本身中声明它呢?我将省略
row
的声明和第一次赋值:编辑:根据 shhkalpesh 的回答,您真的应该使用
using< /code> 语句以确保您的阅读器最终关闭。
You're calling
ReadLine
twice on every iteration - once here:and once here:
Change it to only read once per iteration:
(Note that I've also pulled the creation of the
char[]
out of the loop - there's really no need to do that on every iteration. I'd personally make it a private static variable.)A couple of other style points:
text
variable declared? Why not declare it in the loop itself?I would elide the declaration and first assignment of
row
:EDIT: As per shahkalpesh's answer, you really should use a
using
statement to make sure your reader is closed at the end.