C# 读取文件内容


读取文件内容有三种方式

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

全部读取到字符串变量

string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

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

 

一次读取一行

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

 

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

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

System.Console.WriteLine(
"Contents of WriteLines2.txt = "); foreach (string line in lines) { Console.WriteLine("\t" + line); }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM