टेक्स्ट फ़ाइलें पढ़ने के लिए, C# में StreamReader क्लास का उपयोग करें।
आप जिस फ़ाइल को पढ़ना चाहते हैं उसका नाम जोड़ें:
StreamReader sr = new StreamReader("hello.txt");
ReadLine() विधि का उपयोग करें और फ़ाइल की सामग्री को स्ट्रिंग में प्राप्त करें:
using (StreamReader sr = new StreamReader("hello.txt")) {
str = sr.ReadLine();
}
Console.WriteLine(str);
आइए निम्न कोड देखें:
उदाहरण
using System.IO;
using System;
public class Program {
public static void Main() {
string str;
using (StreamWriter sw = new StreamWriter("hello.txt")) {
sw.WriteLine("Hello");
sw.WriteLine("World");
}
using (StreamReader sr = new StreamReader("hello.txt")) {
str = sr.ReadLine();
}
Console.WriteLine(str);
}
}
यह "hello.text" फ़ाइल बनाता है और उसमें टेक्स्ट जोड़ता है। उसके बाद, StreamReader क्लास का उपयोग करके यह आपकी फ़ाइल की पहली पंक्ति पढ़ता है:
आउटपुट
निम्न आउटपुट है।
Hello