टेक्स्ट फाइल पढ़ना
StreamReader का उपयोग करके टेक्स्ट फाइल लाइन दर लाइन पढ़ें:
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();
}
}
}
बाइनरी फाइल पढ़ना
BinaryReader और BinaryWriter का उपयोग करें:
using System.IO;
namespace BinaryFileApplication {
class Program {
static void Main(string[] args) {
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
// फाइल बनाएं और लिखें
try {
bw = new BinaryWriter(new FileStream("mydata", FileMode.Create));
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
bw.Close();
} catch (IOException e) {
Console.WriteLine(e.Message + "\n Cannot create/write file.");
return;
}
// फाइल पढ़ें
try {
br = new BinaryReader(new FileStream("mydata", FileMode.Open));
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
br.Close();
} catch (IOException e) {
Console.WriteLine(e.Message + "\n Cannot read file.");
}
Console.ReadKey();
}
}
}
अन्य तरीके:
File.ReadAllText()- पूरी फाइल एक स्ट्रिंग मेंFile.ReadAllLines()- सभी लाइन्स स्ट्रिंग ऐरे मेंFile.ReadLines()- लेज़ी एन्यूमरेशन (बड़ी फाइल्स के लिए)