StreamReader और StreamWriter क्लासेस का इस्तेमाल डेटा से टेक्स्ट फाइल तक पढ़ने और लिखने के लिए किया जाता है।
टेक्स्ट फ़ाइल पढ़ें -
Using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("d:/new.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
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);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("students.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
} आउटपुट
Jack Tom