Search…

Tổng Hợp Các Phương Pháp Đọc Ghi File với C#

27/09/20201 min read
Các phương pháp đọc ghi file với C# cho nhiều trường hợp sử dụng.

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");
}
IO Stream

IO Stream Co., Ltd

30 Trinh Dinh Thao, Hoa Thanh ward, Tan Phu district, Ho Chi Minh city, Vietnam
+84 28 22 00 11 12
developer@iostream.co

383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2024