C#-文件读取

三种读取文件的方法:

1、全部读取

2、按行读取

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

代码:

#region 读取文件内容

#region 全部读取到字符串变量
string text = System.IO.File.ReadAllText(@"E:1---软件1---C#上位机1---USB-CAN上位机界面1---C#代码1---上位机代码Test.txt");

System.Console.WriteLine("Contents of Test.txt = {0}", text);
#endregion

#region 一次读取一行
int counter = 0;
string line;

System.IO.StreamReader file =
new System.IO.StreamReader(@"E:1---软件1---C#上位机1---USB-CAN上位机界面1---C#代码1---上位机代码 est.txt");
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}

file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
#endregion

#region 全部读取到字符串数组中,每个数组元素存储一行文本
string[] lines = System.IO.File.ReadAllLines(@"E:1---软件1---C#上位机1---USB-CAN上位机界面1---C#代码1---上位机代码Test.txt");
System.Console.WriteLine("Contents of Test.txt = ");
foreach (string line2 in lines)
{
Console.WriteLine(" " + line2);
}
#endregion

Console.Read();
#endregion

路径需要更换为定义文件路径

原文地址:https://www.cnblogs.com/byxzwz/p/13222009.html