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

Đọc và ghi file text trong C#

Dùng StreamReader (đọc) và StreamWriter (ghi).

Đọc file text

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: " + e.Message);
            }
            Console.ReadKey();
        }
    }
}

Ghi file text

using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Jack", "Tom" };
            
            // Ghi
            using (StreamWriter sw = new StreamWriter("students.txt"))
            {
                foreach (string s in names)
                    sw.WriteLine(s);
            }
            
            // Đọc lại
            using (StreamReader sr = new StreamReader("students.txt"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                    Console.WriteLine(line);
            }
            Console.ReadKey();
        }
    }
}

Kết quả

Jack
Tom

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

// Ghi
File.WriteAllLines("file.txt", names);
File.WriteAllText("file.txt", "content");

// Đọc
string[] lines = File.ReadAllLines("file.txt");
string content = File.ReadAllText("file.txt");

// Async
await File.WriteAllLinesAsync("file.txt", names);
string[] lines = await File.ReadAllLinesAsync("file.txt");