用C#程式一次性將檔案內容讀入到字串


使用ReadToEnd()方法讀取字串中的檔案內容。

在StreamReader中進行設定並讀取檔案−

using (StreamReader sr = new StreamReader("new.txt")){
   string res = sr.ReadToEnd();
   Console.WriteLine(res);
}

以下是完整程式碼−

示例

 動態演示

using System.IO;
using System;

public class Demo {
   public static void Main() {
      using (StreamWriter sw = new StreamWriter("new.txt")) {
         sw.WriteLine("One");
         sw.WriteLine("Two");
      }
      using (StreamReader sr = new StreamReader("new.txt")) {
         string res = sr.ReadToEnd();
         Console.WriteLine(res);
      }
   }
}

它建立了檔案“new.text”並向其中添加了文字。之後,使用StreamReader類和ReadToEnd()方法,它讀取檔案的內容並將其放入字串中−

輸出

以下為輸出。

One
Two

更新日期:2020年04月03日

228瀏覽量

啟動你的 職業生涯

完成課程獲得認證

開始
廣告