सबसे पहले, StreamWriter वर्ग का उपयोग करके एक फ़ाइल बनाएं और उसमें सामग्री जोड़ें -
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");
} अब सभी पंक्तियों को पढ़ने के लिए ReadAllLines() विधि का उपयोग करें। इसके साथ, लंबाई की संपत्ति का उपयोग लाइनों की गिनती प्राप्त करने के लिए किया जाना है -
int count = File.ReadAllLines("hello.txt").Length; ये रहा पूरा कोड -
उदाहरण
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);
}
} आउटपुट
Number of lines: 3