c# - StreamReader 获取和设置位置

标签 c# stream position streamreader

我只是想读取一个大型 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/

相关文章:

c++ - 使用 boost::iostreams::tee_device?

stream - computeHash byte[] 和 Stream 的区别

position - SKSpriteNode 上的 CGPoint x 无法正常工作(一半节点超出屏幕)

html - 不同位置的相同div? (CSS)

c# - 文件或程序集无法加载错误

javascript - NodeJS - 直接流式传输到 Azure 数据湖

c# - 在不同文档中查找相似段落

css - 溢出内部溢出隐藏和位置相对祖 parent

c# - Visual Studio 2010 在分析报告后进行分析时崩溃

c# - 在运行时从自定义 UITypeEditor 中的属性上插入自定义 TypeConverter