user12017098
user12017098

Reputation:

Streamreader reading the same line multiple times C#

My old method (other than being wrong in general) takes too long to get multiple lines from a file and then store the parameters into a dictionary. Essentially it's open file, grab every second line one at a time, modify the line then store the data (line pos and the first element of the line (minus) ">") close the file and then repeat.

for (int i = 0; i < linecount - 1; i += 2)
{
    string currentline = File.ReadLines 
    (datafile).Skip(i).Take(1).First();
    string[] splitline = currentline.Split(' ');
    string filenumber = splitline[0].Trim('>');
}   for (int i = 0; i < linecount - 1; i += 2)

Upvotes: 0

Views: 1207

Answers (2)

mjwills
mjwills

Reputation: 23984

The issue is that you only ever read the first line of the file. To solve this you need to ensure you call sr.ReadLine() on every iteration through the loop. This would look like:

using (StreamReader sr = File.OpenText(datafile))
{
    string line = sr.ReadLine();
    while (line != null)
    {
        count = count ++;
        if (count % 2 == 0)
        {
            string[] splitline = line.Split(' ');
            string datanumber = splitline[0].Trim('>');
            index.Add(datanumber, count);
        }

        line = sr.ReadLine();
    }
}

This means on each iteration, the value of line will be a new value (from the next line of the file).

Upvotes: 1

pakeha_by
pakeha_by

Reputation: 2244

You need to read next line inside while loop, otherwise loop body will always analyse first line (that's why there are Dictionary error) and never exist:

while (line != null)
{
    // your current code here
    line = sr.ReadLine();
}

Upvotes: 2

Related Questions