Tổng hợp các cách đọc file text
* filePath
là đường dẫn đến file ví dụ "D:/data/profile.txt"
.
Đọc toàn bộ file text 1 lần
Đọc toàn bộ dòng từ file text
string[] lines = System.IO.File.ReadAllLines(@filePath);
Đọc toàn bộ chuỗi từ file text
string text = System.IO.File.ReadAllText(@filePath);
Tổng hợp các cách ghi file text
Ghi toàn bộ file text 1 lần
Ghi toàn bộ dòng vào file text
string[] lines = { "Line 1", "Line 2", "Line 3" }; System.IO.File.WriteAllLines(@filePath, lines);
Ghi toàn bộ chuỗi vào file text
string text = "Hello Text"; System.IO.File.WriteAllLines(@filePath, text);
Ghi từng dòng vào file text
Sử dụng StreamWriter
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@filePath)) { foreach (string line in lines) { file.WriteLine(line); } }
Ghi thêm dòng vào file text
Thêm tham số true
vào tham số thứ 2 của StreamWriter
.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@filePath, true)) { file.WriteLine("Line 4"); }