------讀取的數據比較小的時候:
如果你要讀取的文件內容不是很多,可以使用 File.ReadAllText(filePath) 或指定編碼方式 File.ReadAllText(FilePath, Encoding)的方法。它們都一次性將文本內容全部讀完,並返回一個包含全部文本內容的字符串
用string接收
string str1 = File.ReadAllText(@"c:\temp\a.txt"); //也可以指定編碼方式
string str2 = File.ReadAllText(@"c:\temp\a.txt", Encoding.ASCII);
也可以使用方法File.ReadAllLines,該方法一次性讀取文本內容的所有行,返回一個字符串數組,數組元素是每一行的內容
string[] strs1 = File.ReadAllLines(@"c:\temp\a.txt"); // 也可以指定編碼方式 string[] strs2 = File.ReadAllLines(@"c:\temp\a.txt", Encoding.ASCII);
-----讀取數據比較大的時候,采用流的方式:
當文本的內容比較大時,我們就不要將文本內容一次性讀完,而應該采用流(Stream)的方式來讀取內容。
.Net為我們封裝了StreamReader類,它旨在以一種特定的編碼從字節流中讀取字符。StreamReader類的方法不是靜態方法,所以要使用該類讀取文件首先要實例化該類,在實例化時,要提供讀取文件的路徑。
StreamReader sR1 = new StreamReader(@"c:\temp\a.txt");
// 讀一行
string nextLine = sR.ReadLine();
// 同樣也可以指定編碼方式
StreamReader sR2 = new StreamReader(@"c:\temp\a.txt", Encoding.UTF8);
FileStream fS = new FileStream(@"C:\temp\a.txt", FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader sR3 = new StreamReader(fS);
StreamReader sR4 = new StreamReader(fS, Encoding.UTF8);
FileInfo myFile = new FileInfo(@"C:\temp\a.txt");
// OpenText 創建一個UTF-8 編碼的StreamReader對象
StreamReader sR5 = myFile.OpenText();
// OpenText 創建一個UTF-8 編碼的StreamReader對象
StreamReader sR6 = File.OpenText(@"C:\temp\a.txt");
獲取到大的文件后,都是流的返回形式
可以用流的讀取方法讀出數據,返回類型是String類型
// 讀一行
string nextLine = sR.ReadLine();
// 讀一個字符
int nextChar = sR.Read();
// 讀100個字符
int n = 100; char[] charArray = new char[n]; int nCharsRead = sR.Read(charArray, 0, n);
// 全部讀完
string restOfStream = sR.ReadToEnd();
使用完StreamReader之后,不要忘記關閉它: sR.Close();
假如我們需要一行一行的讀,將整個文本文件讀完,下面看一個完整的例子:
StreamReader sR = File.OpenText(@"C:\temp\a.txt"); string nextLine; while ((nextLine = sR.ReadLine()) != null) { Console.WriteLine(nextLine); } sR.Close();