第一種:
/// <summary> /// 讀取txt文件內容 /// </summary> /// <param name="Path">文件地址</param> public void ReadTxtContent(string Path) { StreamReader sr = new StreamReader(Path, Encoding.Default); string content; while ((content = sr.ReadLine()) != null) { Console.WriteLine(content.ToString()); } }
第二種:
它們都一次將文本內容全部讀完,並返回一個包含全部文本內容的字符串
string str = File.ReadAllText(@"c:\temp\ascii.txt");
// 也可以指定編碼方式
string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII);
也可以使用方法File.ReadAllLines。該方法返回一個字符串數組。每一行都是一個數組元素。
string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt");
// 也可以指定編碼方式
string[] strs2 = File.ReadAllLines(@"c:\temp\ascii.txt", Encoding.ASCII);