StreamReader获取并设置位置 [英] StreamReader get and set position

查看:390
本文介绍了StreamReader获取并设置位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想读取一个大型CSV文件并将Stream位置保存在列表中.之后,我必须从列表中读取位置,并将Streamreader的位置设置为该char并读取一行! 但是在我读完第一行并用

i simply want to read a large CSV-File and save the Stream position in a list. After that i have to read the position from the list and set the position of the Streamreader to that char and read a line!! But after i read the first line and return the streamposition with

StreamReader r = new StreamReader("test.csv");
r.readLine();
Console.WriteLine(r.BaseStream.Position); 

我得到"177",这是文件中的所有字符! (这只是一个简短的示例文件) 我没有在这里找到能帮助我的东西!

i get "177", which are the total chars in the file! (it's only a short examplefile) i didn't found anything like that here arround which helped me!

为什么?

完整方法:

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级文化水平

And so on it's a Program exercise: http://clean-code-advisors.com/ressourcen/application-katas (Katas CSV viewer) I'm currently at literation 3

推荐答案

StreamReader使用的是缓冲流,因此StreamReader.BaseStream.Position可能会比使用ReadLine实际读取"的字节数提前

StreamReader is using a buffered stream, and so StreamReader.BaseStream.Position will likely be ahead of the number of bytes you have actually 'read' using ReadLine.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆