在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