Search code examples
c#streamwriter

How do i find out the Number of Lines in a text file?


string s;

Console.WriteLine("Enter What you want to write in your File : ");
s = Convert.ToString(Console.ReadLine());

using (StreamWriter sw = new StreamWriter(@"E:/File.txt"))
{
     sw.Write(s);
     sw.Close();
}

using (StreamReader r = new StreamReader(@"E:/File.txt"))
{
     char[] buffer = new char[1024];
     int read;
     int line = 0;
     while ((read = r.ReadBlock(buffer, 0, buffer.Length)) > 0)
     {
          for (int i = 0; i < read; i++)
          {
               if (buffer[i] == '\n' && buffer[i]=='\r')
               {
                    line++;       
               }
          }               
          //Console.WriteLine(buffer[i]);
     }
     Console.WriteLine("Total Lines Are : " + line);
}

Im trying to find out the total number of lines so that i may be able to append it more precisely but im quite unable to do so. It outputs Zero whenever i run it. Sorry for being a Noob. :)


Solution

  • Why not direct

     using System.IO;
     using System.Linq;
    
     ... 
    
     int count = File.ReadLines(@"E:\File.txt").Count();