使用StreamReader读入C#中的文件
要读取文本文件,请使用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