在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 剪简短的新年祝福语
13 毕业贺卡老师祝福语简短
14 新年送老师简短祝福语
15 同事调动的祝福语简短
16 发给导师的祝福语简短
17 对同事简短生日祝福语
18 表达家人的祝福语简短