StreamReader get and set position

江枫思渺然 提交于 2019-12-21 11:24:04

问题


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:


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.



来源:https://stackoverflow.com/questions/20029814/streamreader-get-and-set-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!