如何在 C# 中打开纯文本文件?
csharpprogrammingserver side programming更新于 2025/5/24 17:07:17
要打开纯文本文件,请使用 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("无法读取文件:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
输出
无法读取文件: Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".

