StreamReader get and set position

2020-07-07 10:52发布

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); 

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!

Why?

Full methode:

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;
}

The file looks like this:

name;age;city
Simon;20;Stuttgart
Daniel;34;Ostfildern

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

1条回答
smile是对你的礼貌
2楼-- · 2020-07-07 11:27

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.

There's a discussions of how to do what you're trying to do in this SO question.

查看更多
登录 后发表回答