Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader get and set position

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

like image 553
coolerfarmer Avatar asked Nov 17 '13 10:11

coolerfarmer


People also ask

Which method sets the position in the current Filestream?

Python File tell() Method The tell() method returns the current file position in a file stream.

What is StreamReader and StreamWriter?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.

What does StreamReader mean in C#?

C# StreamReader is used to read characters to a stream in a specified encoding. StreamReader. Read method reads the next character or next set of characters from the input stream. StreamReader is inherited from TextReader that provides methods to read a character, block, line, or all content.


1 Answers

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.

like image 86
Ergwun Avatar answered Sep 18 '22 08:09

Ergwun