在 C# 中读取和写入文本文件
csharpprogrammingserver side programming更新于 2025/9/1 13:07:17
StreamReader 和 StreamWriter 类用于读取和写入文本文件的数据。
读取文本文件 −
Using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
// 创建 StreamReader 实例以读取文件。
// using 语句还会关闭 StreamReader。
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

