StreamReader sr = new StreamReader(string path);
StreamReader sr = new StreamReader(string path, Encoding encoding);
StreamReader sr = new StreamReader(Stream stream);
主要方法
方法
说明
Read()
读取下一个字符(返回int)
ReadLine()
读取一行文本(不包含换行符)
ReadToEnd()
读取流到末尾,返回字符串
Peek()
查看下一个字符(不移除)
Close() / Dispose()
关闭释放资源
3. StreamWriter 用法详解
常用构造函数
StreamWriter sw = new StreamWriter(string path);
StreamWriter sw = new StreamWriter(string path, bool append);
StreamWriter sw = new StreamWriter(Stream stream);
主要方法
方法
说明
Write(string)
写字符串
WriteLine(string)
写字符串并换行
Flush()
刷新缓冲区,强制写入
Close() / Dispose()
关闭释放资源
4. 结合示例:读写文件操作
示例:读取文本文件内容
using System;
using System.IO;
using System.Text;
class Program {
static void Main() {
string filePath = "example.txt";
using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8)) {
string line;
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
}
示例:写入文本文件内容(覆盖写)
using System;
using System.IO;
class Program {
static void Main() {
string filePath = "output.txt";
using (StreamWriter sw = new StreamWriter(filePath, false)) { // false覆盖写
sw.WriteLine("Hello World!");
sw.WriteLine("这是第二行文本。");
}
}
}
示例:追加写入文本文件
using (StreamWriter sw = new StreamWriter(filePath, true)) { // true追加写
sw.WriteLine("追加的新行");
}
发表回复