使用 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