StreamReader से टेक्स्ट फाइल पढ़ना
प्लेन टेक्स्ट फाइल खोलने के लिए StreamReader क्लास का उपयोग करें:
StreamReader sr = new StreamReader("d:/new.txt")
फाइल का कंटेंट प्रदर्शित करें:
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
पूर्ण कोड उदाहरण
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
using (StreamReader sr = new StreamReader("d:/new.txt")) {
string line;
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
आउटपुट (यदि फाइल न मिले)
The file could not be read: Could not find a part of the path...
सर्वोत्तम अभ्यास:
usingस्टेटमेंट ऑटोमैटिकली फाइल बंद करता है (IDisposable)- बड़ी फाइल्स के लिए
File.ReadLines()उपयोग करें (मेमोरी कुशल) - एन्कोडिंग निर्दिष्ट करें:
new StreamReader(path, Encoding.UTF8)
सरल विकल्प:
string content = File.ReadAllText("d:/new.txt");
Console.WriteLine(content);