StreamReader और StreamWriter
StreamReader और StreamWriter क्लासेस टेक्स्ट फाइल्स से डेटा पढ़ने और लिखने के लिए उपयोग की जाती हैं।
टेक्स्ट फाइल पढ़ना:
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();
}
}
}
टेक्स्ट फाइल लिखना:
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
string[] names = new string[] { "Jack", "Tom" };
using (StreamWriter sw = new StreamWriter("students.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
}
// फाइल पढ़कर दिखाएं
string line = "";
using (StreamReader sr = new StreamReader("students.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
आउटपुट:
Jack Tom
सर्वोत्तम अभ्यास:
usingस्टेटमेंट - ऑटोमैटिक डिस्पोज़ल (फाइल क्लोज़)- एन्कोडिंग निर्दिष्ट करें:
new StreamWriter(path, false, Encoding.UTF8) - अपेंड मोड:
new StreamWriter(path, true)(दूसरा पैरामीटर append) - आधुनिक API:
File.WriteAllLines,File.ReadAllLines,File.AppendAllLines