使用 C# 中的 StreamReader 讀取檔案


要讀取文字檔案,請在 C# 中使用 StreamReader 類。

新增要讀取的檔案的名稱 -

StreamReader sr = new StreamReader("hello.txt");

使用 ReadLine() 方法並在字串中獲取檔案的內容 -

using (StreamReader sr = new StreamReader("hello.txt")) {
   str = sr.ReadLine();
}
Console.WriteLine(str);

讓我們看以下程式碼 -

示例

 線上演示

using System.IO;
using System;

public class Program {
   public static void Main() {
      string str;
      using (StreamWriter sw = new StreamWriter("hello.txt")) {
         sw.WriteLine("Hello");
         sw.WriteLine("World");
      }
      using (StreamReader sr = new StreamReader("hello.txt")) {
         str = sr.ReadLine();
      }
      Console.WriteLine(str);
   }
}

它建立檔案“hello.text”並將文字新增到其中。之後,使用 StreamReader 類讀取檔案的**第一**行 -

輸出

以下是輸出。

Hello

更新於: 2020 年 4 月 3 日

454 次瀏覽

啟動您的 Career

完成課程,即可獲得認證

開始
廣告
© . All rights reserved.