[英]My StreamReader code is reading only every other line 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);
}
}
您在每次迭代中都兩次調用ReadLine
在這里一次:
while (tr.ReadLine() != null)
然后在這里:
string words = tr.ReadLine();
將其更改為每個迭代僅讀取一次:
char[] delimiterChar = { ';' };
string words;
while ((words = tr.ReadLine()) != null)
{
int i = 0;
text = words.Split(delimiterChar);
...
}
(請注意,我還拉了創建char[]
圈外的-真的沒有必要做,在每個迭代上我個人使它成為一個私有靜態變量)。
其他一些風格要點:
text
變量在哪里聲明? 為什么不在循環本身中聲明它? 我會忽略row
的聲明和第一次分配:
DataRow row = t.NewRow();
編輯:根據shahkalpesh的回答,您確實應該使用using
語句來確保您的讀者在最后關閉。
那是因為您要兩次撥打ReadLine
。
更好的方法可能是:
while (!tr.EndOfStream)
編輯:最好將代碼包含在using
子句中。
using (TextReader tr = new StreamReader("aplusixdata.txt"))
{
//.. your code here that reads the file line by line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.