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

Các cách nhanh nhất đọc file text line by line trong C#

Có nhiều cách đọc file text line by line. Bao gồm StreamReader.ReadLine, File.ReadLines, v.v. Xét file text trên máy local có nội dung như sau.

Dùng StreamReader.ReadLine

C# StreamReader dùng để đọc characters từ stream với encoding chỉ định. StreamReader.Read đọc character tiếp theo hoặc set characters từ input stream. StreamReader kế thừa từ TextReader cung cấp methods đọc character, block, line, hoặc toàn bộ content.

Ví dụ

using System; 
using System.IO; 
using System.Text; 

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            using (var fileStream = File.OpenRead(@"D:\Demo\Demo.txt")) 
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { 
                string line; 
                while ((line = streamReader.ReadLine()) != null) { 
                    Console.WriteLine(line); 
                } 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Output

Hi All!! Hello Everyone!! How are you?

Dùng File.ReadLines

Phương thức File.ReadAllLines() mở file text, đọc tất cả lines vào IEnumerable<string>, rồi đóng file.

Ví dụ

using System; 
using System.IO; 

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            var lines = File.ReadLines(@"D:\Demo\Demo.txt"); 
            foreach (var line in lines) { 
                Console.WriteLine(line); 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Output

Hi All!! Hello Everyone!! How are you?

Dùng File.ReadAllLines

Rất giống ReadLines. Tuy nhiên trả về String[] chứ không phải IEnumerable<String> cho phép random access lines.

Ví dụ

using System; 
using System.IO; 

namespace DemoApplication { 
    public class Program { 
        static void Main(string[] args) { 
            var lines = File.ReadAllLines(@"D:\Demo\Demo.txt"); 
            for (var i = 0; i < lines.Length; i += 1) { 
                var line = lines[i]; 
                Console.WriteLine(line); 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Output

Hi All!! Hello Everyone!! How are you?

So sánh hiệu suất và Memory

Phương pháp Memory Lazy/Deferred Random Access Phù hợp
File.ReadLines Thấp (streaming) Có (IEnumerable) Không File lớn, xử lý tuần tự
File.ReadAllLines Cao (load all) Không (string[]) Có File nhỏ, cần random access
StreamReader.ReadLine Thấp nhất Có (manual) Không File rất lớn, kiểm soát chi tiết, custom encoding

Các cách khác

1. File.ReadAllText (đọc toàn bộ)

string content = File.ReadAllText(@"D:\Demo\Demo.txt");
var lines = content.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

2. Async với StreamReader (ASP.NET Core)

using (var reader = new StreamReader(File.OpenRead(path), Encoding.UTF8)) {
    string line;
    while ((line = await reader.ReadLineAsync()) != null) {
        // Process line
    }
}

3. System.IO.Pipelines (High performance .NET Core 2.1+)

using System.IO.Pipelines;

var pipe = new Pipe();
Task writing = FillPipeAsync(pipe.Writer, filePath);
Task reading = ReadPipeAsync(pipe.Reader);

Best Practice

  • File nhỏ (< 100MB): File.ReadAllLines đơn giản, nhanh
  • File lớn (> 100MB): File.ReadLines hoặc StreamReader (memory efficient)
  • Cần encoding tùy chỉnh: StreamReader với Encoding.UTF8/Unicode
  • Async/High throughput: StreamReader.ReadLineAsync hoặc Pipelines
  • Luôn dùng using để đảm bảo dispose file handle