C#程序可一次将文件内容读入字符串
使用ReadToEnd()方法读取字符串中文件的内容。
在StreamReader下设置它并读取文件-
using (StreamReader sr = new StreamReader("new.txt")){
string res = sr.ReadToEnd();
Console.WriteLine(res);
}以下是完整的代码-
示例
using System.IO;
using System;
public class Demo {
public static void Main() {
using (StreamWriter sw = new StreamWriter("new.txt")) {
sw.WriteLine("One");
sw.WriteLine("Two");
}
using (StreamReader sr = new StreamReader("new.txt")) {
string res = sr.ReadToEnd();
Console.WriteLine(res);
}
}
}它创建文件“new.text”并向其中添加文本。之后,使用StreamReader类和ReadToEnd()方法,它将文件的内容读取为字符串-
输出结果
以下是输出。
One Two
热门推荐
2 红丝绒戚风蛋糕
3 夹心小甜点
4 南瓜甜点
6 粘米粉蒸蛋糕
7 酸奶华夫饼
9 红柚鸡蛋糕
10 葡萄干蛋糕
11 紫薯蛋糕卷
13 纸杯裱花小蛋糕
14 果酱奶酪蛋糕
15 日式樱花蔓越莓大福
16 草莓蛋糕卷
17 卡仕达长崎杯子蛋糕