在C#中读写文本文件
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("无法读取该文件:");
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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短