如何在 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