Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

Posted

FileStream and StreamReader

 

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

 

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:

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...