StreamReader 类 (System.io) | Microsoft 官方文档 StreamWriter 类 (System.IO) | Microsoft 官方文档 一、文
StreamReader 类 (System.io) | Microsoft 官方文档
StreamWriter 类 (System.IO) | Microsoft 官方文档
TextReader/TextWriter:文本读写,抽象类
构造函数:默认编码为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);
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
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));
}
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);
}
}
using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
StreamWriter类允许直接将字符和字符串写入文件
//保留文件现有数据,以追加写入的方式打开d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true)) //true 表示追加
{
//向文件写入新字符串,并关闭StreamWriter
sw.WriteLine("Another File Operation Method");
}
到此这篇关于C#使用StreamReader和StreamWriter类读写操作文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。
--结束END--
本文标题: C#使用StreamReader和StreamWriter类读写操作文件
本文链接: https://www.lsjlt.com/news/148473.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0