2013年4月3日 星期三

[C#]快速讀取、寫入檔案的方法

C#提供一些快速的Method可以直接寫入或是讀取檔案,善用的話可以節省一些時間
以下三個static methods只需要一個步驟就可把資料從檔案讀到記憶體中,傳入參數都是讀取檔案的路徑
File.ReadAllText(path)                        // (回傳string)
File.ReadAllLines(path)                       // (回傳array of strings)
File.ReadAllBytes(path)                       // (回傳一個byte array)

下列四個static methods同樣只需要一個步驟就可把資料寫入到檔案中,傳入參數是路徑以及寫入的資料
File.WriteAllText(path, string)
File.WriteAllLines(path, array of strings)
File.WriteAllBytes(path, bytes)      
File.AppendAllText(path, string)              // (適合用在log file)
File.ReadAllLines和File.ReadLines看起來很像,但是ReadAllLines會一次把所有資料讀到記憶體中
ReadLines會回傳一個IEnumerable<string>,不會一次把所有資料讀到記憶體中

沒有留言:

張貼留言