在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 教师闺蜜祝福语简短