这篇文章介绍了C#使用StreamReader和StreamWriter类读写操作文件的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
StreamReader 类 (System.IO) | Microsoft 官方文档
StreamWriter 类 (System.IO) | Microsoft 官方文档
一、文本读写类:
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());
}
三、StreamWriter类,写文件
实例:
StreamWriter类允许直接将字符和字符串写入文件
//保留文件现有数据,以追加写入的方式打开d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true)) //true 表示追加
{
//向文件写入新字符串,并关闭StreamWriter
sw.WriteLine("Another File Operation Method");
}
到此这篇关于C#使用StreamReader和StreamWriter类读写操作文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#使用StreamReader和StreamWriter类读写操作文件


基础教程推荐
猜你喜欢
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中 Json 序列化去掉null值的方法 2022-11-18
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- 实例详解C#实现http不同方法的请求 2022-12-26
- Unity shader实现高斯模糊效果 2023-01-16
- C#中的Linq to JSON操作详解 2023-06-08
- C# 解析XML和反序列化的示例 2023-04-14