StreamReader获取和设置位置

10

我只想读取一个大型CSV文件,并将流位置保存在列表中。之后,我必须从列表中读取位置,将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查看器)。我目前完成了第三个迭代。


你的CSV文件有多少行?因为如果它只有1行,在StreamReader上调用ReadLine()应该会让你感到惊讶,因为你已经到达了末尾。 - Darin Dimitrov
测试文件有11行,最终文件大约1.5GB ;) - coolerfarmer
好的,你能展示一下你的“testfile”文件以及你用来读取它的确切代码吗? - Darin Dimitrov
一个对我有效的解决方案在这里:https://dev59.com/ZnRA5IYBdhLWcg3wyBD1#22975649 - Eamon
可能是Tracking the position of the line of a streamreader的重复问题。 - Jim Fell
1个回答

19

StreamReader 使用的是缓冲流,因此 StreamReader.BaseStream.Position 很可能会超过使用 ReadLine 实际读取的字节数。

关于如何实现你尝试做的事情,在这个 SO 问题中有讨论。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接