10

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
coolerfarmer
  • 216
  • 1
  • 4
  • 12
  • How many lines does your CSV file have? Because if it has only 1 line, calling `ReadLine()` on the StreamReader should surprise you that you get to the end. – Darin Dimitrov Nov 17 '13 at 10:55
  • The testfile has 11 lines, the final file is about 1,5GB big ;) – coolerfarmer Nov 17 '13 at 10:57
  • Alright, could you show your `testfile` and also the exact code you are using to read it? – Darin Dimitrov Nov 17 '13 at 10:58
  • A solution that worked for me is here: http://stackoverflow.com/a/22975649/718033 – Eamon Apr 09 '14 at 23:22
  • Possible duplicate of [Tracking the position of the line of a streamreader](https://stackoverflow.com/questions/10189270/tracking-the-position-of-the-line-of-a-streamreader) – Jim Fell Oct 24 '19 at 18:45

1 Answers1

19

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.

Community
  • 1
  • 1
Ergwun
  • 12,579
  • 7
  • 56
  • 83