 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to count the number of lines in a file
Firstly, create a file using StreamWriter class and add content to it −
using (StreamWriter sw = new StreamWriter("hello.txt")) {    sw.WriteLine("This is demo line 1");    sw.WriteLine("This is demo line 2");    sw.WriteLine("This is demo line 3"); } Now use the ReadAllLines() method to read all the lines. With that, the Length property is to be used to get the count of lines −
int count = File.ReadAllLines("hello.txt").Length; Here is the complete code −
Example
using System; using System.Collections.Generic; using System.IO; public class Program {    public static void Main() {       using (StreamWriter sw = new StreamWriter("hello.txt")) {          sw.WriteLine("This is demo line 1");          sw.WriteLine("This is demo line 2");          sw.WriteLine("This is demo line 3");       }       int count = File.ReadAllLines("hello.txt").Length;       Console.WriteLine("Number of lines: "+count);    } }  Output
Number of lines: 3
Advertisements
 