用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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP