C#(101):文件读写(二)利用SteamReader和StreamWrite类处理文本
[StreamReader 类 (System.IO) | Microsoft
Docs](https://docs.microsoft.com/zh-
cn/dotnet/api/system.io.streamreader?view=net-5.0)
[StreamWriter 类 (System.IO) | Microsoft
Docs](https://docs.microsoft.com/zh-
cn/dotnet/api/system.io.streamwriter?view=net-5.0)
一、文本读写类:
TextReader/TextWriter:文本读写,抽象类
1、TextReader文本读 ,其派生类:
- StreamReader :以一种特定的编码从字节流中读取字符。
- StringReader :从字符串读取。
2、TextWriter文本写 ,其派生类:
- StreamWriter :以一种特定的编码向流中写入字符。
- StringWriter :将信息写入字符串, 该信息存储在基础 StringBuilder 中。
- IndentedTextWriter:提供可根据 Tab 字符串标记缩进新行的文本编写器。
- HttpWriter:提供通过内部 TextWriter 对象访问的 HttpResponse 对象。
- HtmlTextWriter:将标记字符和文本写入 ASP.NET 服务器控件输出流。 此类提供 ASP.NET 服务器控件在向客户端呈现标记时使用的格式化功能。
二、StreamReader类,读文件
1、实例:
构造函数:默认编码为UTF-8
StreamReader srAsciiFromFile = new StreamReader("C:\\Temp\\Test.txt", System.Text.Encoding.ASCII);
StreamReader srAsciiFromStream = new StreamReader( (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),System.Text.Encoding.ASCII);
1、从文件读取文本 Read(),Peek()
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
2、调用其ReadAsync()方法以异步方式读取文件。
static async Task Main()
{
await ReadAndDisplayFilesAsync();
}
static async Task ReadAndDisplayFilesAsync()
{
String filename = "C:\\s.xml";
Char[] buffer;
using (var sr = new StreamReader(filename))
{
buffer = new Char[(int)sr.BaseStream.Length];
await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
}
Console.WriteLine(new String(buffer));
}
3、读取一行字符。ReadLine()
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
4、读取到一个操作中的文件的末尾。ReadToEnd()
using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
三、StreamWrite类,写文件
实例:
StreamWriter类允许直接将字符和字符串写入文件
//保留文件现有数据,以追加写入的方式打开d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true)) //true 表示追加
{
//向文件写入新字符串,并关闭StreamWriter
sw.WriteLine("Another File Operation Method");
}