- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- C Program to count the number of lines in a file?
- C program to count characters, lines and number of words in a file
- How to count the number of lines in a text file using Java?
- How to count the total number of lines in the file in PowerShell?
- Write a C program to find total number of lines in an existing file
- C# Program to read all the lines of a file at once
- C# Program to read all the lines one by one in a file
- C# program to count the number of words in a string
- Python Program to Read First n Lines of a File
- C/C++ Program to Count trailing zeroes in factorial of a number?
- Golang Program to Count the Number of Digits in a Number
- C# program to count total bits in a number
- Counting number of lines in text file using java
- How to count the number of words in a text file using Java?
- Program to count number of unique subsequences of a string in C++

Advertisements