使用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 官宣新年祝福语简短