使用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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短