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