Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Mở file text đơn giản trong C#

Sử dụng StreamReader để mở file text đọc:

StreamReader sr = new StreamReader("d:/new.txt")

Đọc từng dòng:

while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
}

Ví dụ hoàn chỉnh

using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (StreamReader sr = new StreamReader("d:/new.txt"))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Không đọc được file:");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

Kết quả (nếu file không tồn tại)

Không đọc được file:
Could not find a part of the path...

Cách ngắn gọn hơn (.NET Core/.NET 5+):

// Đọc toàn bộ
string content = File.ReadAllText("d:/new.txt");
string[] lines = File.ReadAllLines("d:/new.txt");

// Đọc async
string content = await File.ReadAllTextAsync("d:/new.txt");

Luôn dùng using để tự động dispose/close stream.