如何在 C# 中開啟純文字檔案?
要開啟純文字檔案,請使用 StreamReader 類。以下是開啟檔案進行讀取的操作−
StreamReader sr = new StreamReader("d:/new.txt")現在,顯示檔案內容−
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}以下是程式碼 −
示例
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
using (StreamReader sr = new StreamReader("d:/new.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);
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}輸出
The file could not be read: Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP