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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM