Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text file: Reading line by line C#

So, let's say i have a text file with 20 lines, with on each line different text. i want to be able to have a string that has the first line in it, but when i do NextLine(); i want it to be the next line. I tried this but it doesn't seem to work:

string CurrentLine; 
int LastLineNumber;   
Void NextLine() 
{
     System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
     CurrentLine = file.ReadLine(LastLineNumber + 1);
     LastLineNumber++;
}

How would i be able to do this? Thanks in advance.

like image 610
RevoltPlz Avatar asked Feb 18 '14 17:02

RevoltPlz


2 Answers

In general, it would be better if you could design this in a way to leave your file open, and not try to reopen the file each time.

If that is not practical, you'll need to call ReadLine multiple times:

string CurrentLine; 
int LastLineNumber;   
void NextLine() 
{
    // using will make sure the file is closed
    using(System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"))
    {
        // Skip lines
        for (int i=0;i<LastLineNumber;++i)
            file.ReadLine();

        // Store your line
        CurrentLine = file.ReadLine();
        LastLineNumber++;
    }
}

Note that this can be simplified via File.ReadLines:

void NextLine() 
{
    var lines = File.ReadLines("C:\\test.txt");

    CurrentLine = lines.Skip(LastLineNumber).First();
    LastLineNumber++;
}
like image 130
Reed Copsey Avatar answered Oct 13 '22 15:10

Reed Copsey


One simple call should do it:

var fileLines = System.IO.File.ReadAllLines(fileName);

You will want to validate the file exists and of course you still need to watch for blank lines or invalid values but that should give you the basics. To loop over the file you can use the following:

foreach (var singleLine in fileLines) {
   // process "singleLine" here
}

One more note - you won't want to do this with large files since it processes everything in memory.

like image 31
drew_w Avatar answered Oct 13 '22 14:10

drew_w