C# 读取txt格式文件内容

读取文件内容有三种方式

a.全部读取到字符串变量中

b.一次读取一行

c.全部读取到字符串数组中,每个数组元素存储一行文本

一次性全部读取到字符串变量

string text = System.IO.File.ReadAllText(@"D:\test.txt");

System.Console.WriteLine("Contents of WriteText.txt = {0}", text);
View Code

一次读取一行

int counter = 0;  
string line;  
  
System.IO.StreamReader file =   
    new System.IO.StreamReader(@"d:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine(line);  
    counter++;  
}  
  
file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);
View Code

全部读取到字符串数组中,每个数组元素存储一行文本

string[] lines = System.IO.File.ReadAllLines(@"d:\test.txt");
System.Console.WriteLine("txt = ");
foreach (string line in lines)
{
    Console.WriteLine("\t" + line);
}
View Code

 

posted on 2020-12-18 23:03  donchen-c  阅读(7110)  评论(0编辑  收藏  举报