C# 为什么在解析 CSV 或 TSV 文件时只能得到部分结果?
我试图从 100 行的 CSV 文件中获取第二个值。我收到前 42 个值,然后它停止了...没有错误消息,也没有错误处理。我很困惑,并且在时间线上。它还对 TSV 文件执行此操作,但给出前 43 个结果。如果您觉得很奇怪,请帮忙告诉我。
我正在使用streamreader,将每一行读入字符串数组,分割数组并获取第二个值并将其添加到列表中...
string path = @"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
foreach (var line in path)
{
string s = sr.ReadLine();
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);
I am trying to get the second value from a CSV file with 100 rows. I am getting the first 42 values then it stops... no error messege, or error handling at all for that matter. I am perplexed and am on a timeline. It is also doing it for a TSV file, but giving the first 43 results. Please help and let me know if it looks strange to you.
I am using streamreader, reading each line into a string array, splitting the array and taking the second value and adding it to a list...
string path = @"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
foreach (var line in path)
{
string s = sr.ReadLine();
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
path
变量是一个字符串。这意味着当您对其进行foreach
时,您将获得一系列字符 - 'C',然后是 ':',然后是 '\' 等。我认为这不是你打算做什么...这是一个使用
File.ReadLines
:或者:
如果您使用 .NET 3.5 并且不介意一次性读取整个文件,则可以使用
File.ReadAllLines
相反。Your
path
variable is a string. That means when youforeach
over it, you're getting a sequence of characters - 'C' then ':' then '\' etc. I don't think that's what you mean to do...Here's a simpler approach using
File.ReadLines
:Or:
If you're using .NET 3.5 and you don't mind reading the whole file in one go, you can use
File.ReadAllLines
instead.您不小心迭代了文件路径中的字符数而不是字符串中的行数。此更改应该修复以下问题:
You are accidentally iterating over the number of characters in the file path instead of the number of lines in the string. This change should fix that:
这个怎么样:
How about this:
我认为你的意思是:
I think you mean to do: