使用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 送给同桌的祝福语简短