使用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 妈妈生日祝福语简短励志