日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C#使用StreamReader和StreamWriter類讀寫操作文件_C#教程

作者:springsnow ? 更新時間: 2022-07-04 編程語言

StreamReader 類 (System.IO) | Microsoft 官方文檔

StreamWriter 類 (System.IO) | Microsoft 官方文檔

一、文本讀寫類:

TextReader/TextWriter:文本讀寫,抽象類

1、TextReader文本讀,其派生類:

  • StreamReader:以一種特定的編碼從字節(jié)流中讀取字符。
  • StringReader:從字符串讀取。

2、TextWriter文本寫,其派生類:

  • StreamWriter:以一種特定的編碼向流中寫入字符。
  • StringWriter:將信息寫入字符串, 該信息存儲在基礎(chǔ) StringBuilder 中。
  • IndentedTextWriter:提供可根據(jù) Tab 字符串標(biāo)記縮進(jìn)新行的文本編寫器。
  • HttpWriter:提供通過內(nèi)部 TextWriter 對象訪問的 HttpResponse 對象。
  • HtmlTextWriter:將標(biāo)記字符和文本寫入 ASP.NET 服務(wù)器控件輸出流。 此類提供 ASP.NET 服務(wù)器控件在向客戶端呈現(xiàn)標(biāo)記時使用的格式化功能。

二、StreamReader類,讀文件

1、實例:

構(gòu)造函數(shù):默認(rèn)編碼為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、調(diào)用其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類允許直接將字符和字符串寫入文件

//保留文件現(xiàn)有數(shù)據(jù),以追加寫入的方式打開d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true)) //true 表示追加
{
    //向文件寫入新字符串,并關(guān)閉StreamWriter
    sw.WriteLine("Another File Operation Method");
}

原文鏈接:https://www.cnblogs.com/springsnow/p/9428704.html

欄目分類
最近更新