在 C# 中读取文件的不同方法
csharpprogrammingserver side programming更新于 2025/11/25 17:38:00
这里,我们读取两个不同的文件 −
读取文本文件 −
示例
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 "/home/cg/root/4281363/d:/new.txt".
Reading binary file −
示例
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));
} catch (IOException e) {
Console.WriteLine(e.Message + "
无法创建文件。");
return;
}
//写入文件
try {
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
} catch (IOException e) {
Console.WriteLine(e.Message + "
无法写入文件。");
return;
}
bw.Close();
//从文件读取
try {
br = new BinaryReader(new FileStream("mydata", FileMode.Open));
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot open file.");
return;
}
try {
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);
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot read from file.");
return;
}
br.Close();
Console.ReadKey();
}
}
}

