C#-文件读取

三种读取文件的方法:

1、全部读取

#region 全部读取到字符串变量
string text = System.IO.File.ReadAllText(@"E:\TestPath\Test.txt");
System.Console.WriteLine("Contents of Test.txt = {0}", text);
#endregion

2、按行读取

#region 一次读取一行
int counter = 0;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(@"E:\TestPath\Test.txt");
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;//行计数
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
#endregion

3、全部读取到字符串数组中,数组元素存储行文本

#region 全部读取到字符串数组中,每个数组元素存储一行文本
string[] lines = System.IO.File.ReadAllLines(@"E:\TestPath\Test.txt");
System.Console.WriteLine("Contents of Test.txt = ");
foreach (string line2 in lines)
{
Console.WriteLine("\t" + line2);
}
#endregion
posted @ 2022-07-30 18:36  码农阿亮  阅读(6343)  评论(0编辑  收藏  举报