我只是想读取一个大型 CSV 文件并将 Stream 位置保存在列表中。之后我必须从列表中读取位置并将 Streamreader 的位置设置为该字符并读取一行!! 但是在我读完第一行并用
返回流位置之后StreamReader r = new StreamReader("test.csv");
r.readLine();
Console.WriteLine(r.BaseStream.Position);
我得到“177”,这是文件中的总字符数! (这只是一个简短的示例文件) 我在这里没有找到任何对我有帮助的东西!
为什么?
完整方法:
private void readfile(object filename2)
{
string filename = (string)filename2;
StreamReader r = new StreamReader(filename);
string _top = r.ReadLine();
top = new Eintrag(_top.Split(';')[0], _top.Split(';')[1], _top.Split(';')[2]);
int siteindex = 0, index = 0;
string line;
sitepos.Add(r.BaseStream.Position); //sitepos is the a List<int>
while(true)
{
line = r.ReadLine();
index++;
if(!string.IsNullOrEmpty(line))
{
if (index > seitenlaenge)
{
siteindex++;
index = 1;
sitepos.Add(r.BaseStream.Position);
Console.WriteLine(line);
Console.WriteLine(r.BaseStream.Position.ToString());
}
}
else break;
maxsites = siteindex;
}
reading = false;
}
文件看起来像这样:
name;age;city
Simon;20;Stuttgart
Daniel;34;Ostfildern
等等 这是一个程序练习: http://clean-code-advisors.com/ressourcen/application-katas (Katas CSV 查看器)我目前处于文学 3
最佳答案
StreamReader
使用缓冲流,因此 StreamReader.BaseStream.Position
可能会领先于您使用 实际“读取”的字节数ReadLine
.
在 this SO question 中讨论了如何做您想做的事情。 .
关于c# - StreamReader 获取和设置位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029814/