时间:2022-07-31 09:18:17 | 栏目:.NET代码 | 点击:次
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");
}