2 Questions on Read Text File

SIMIN

Regular
Joined
Mar 10, 2008
Messages
92
Hello,
I have 2 questions:

1. I know I can use System.IO.File.ReadAllText() to read the contents of a text file, but that's unneccessary, I just need to read the 1st line of my text file, how can I do it?

2. Also, how can I get the total number of lines in my text file?

Thanks for your help.
 
FileStream and StreamReader

One way is to create a FileStream and then read it as text using a StreamReader:

C#:
using (FileStream fStream = new FileStream(fileName, FileMode.Open)) {
    //Could specify an Encoding here
    using (StreamReader reader = new StreamReader(fStream)) { 

        //Read first line
        string firstLine = reader.ReadLine();

        //Count lines - starting from the line we already read
        int lines = 1;
        while (reader.ReadLine()) {
            lines++;
        }
    }
}

Good luck :cool:
 
Back
Top