C# Programming

C#高效逐行读取文本文件

Spread the love

高效逐行读取文本文件是任何 C# 开发人员都必须掌握的关键技能。无论您是处理日志、解析配置文件还是分析数据集,您选择的方法都会显著影响性能和资源使用。本文探讨了三种常见方法,重点介绍了它们的优缺点,以帮助您根据具体需求选择最佳技术。

目录

使用 File.ReadLines()

File.ReadLines() 方法通常是最有效和最方便的选择,尤其对于大型文件而言。它返回一个 IEnumerable<string>,这意味着它逐行处理文件,而不会一次性将整个内容加载到内存中。这种延迟加载可以防止在处理海量数据集时出现潜在的 OutOfMemoryException 错误。


using System;
using System.IO;
using System.Linq;

public class ReadLinesExample
{
    public static void Main(string[] args)
    {
        string filePath = "myFile.txt"; 

        try
        {
            foreach (string line in File.ReadLines(filePath))
            {
                Console.WriteLine(line); 
                //在此处处理每一行
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"文件未找到:{filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
}

使用 File.ReadAllLines()

File.ReadAllLines() 提供了更简单的语法,将所有行读取到一个字符串数组中。但是,这种方法会将整个文件加载到内存中,这使得它对于大型文件效率低下且可能存在问题。它最适合用于内存消耗不是主要问题的较小文件。


using System;
using System.IO;

public class ReadAllLinesExample
{
    public static void Main(string[] args)
    {
        string filePath = "myFile.txt";

        try
        {
            string[] lines = File.ReadAllLines(filePath);
            foreach (string line in lines)
            {
                Console.WriteLine(line); 
                //在此处处理每一行
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"文件未找到:{filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
}

使用 StreamReader.ReadLine()

StreamReader.ReadLine() 提供了最细粒度的控制。您可以使用循环一次读取一行,允许在读取下一行之前自定义处理每一行。此方法需要使用 using 语句进行显式资源管理,以确保正确释放 StreamReader


using System;
using System.IO;

public class StreamReaderExample
{
    public static void Main(string[] args)
    {
        string filePath = "myFile.txt";

        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line); 
                    //在此处处理每一行
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"文件未找到:{filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
}

选择正确的方法

对于大多数场景,尤其是在处理大型文件时,File.ReadLines() 由于其效率和易用性而成为推荐的方法。File.ReadAllLines() 仅适用于较小的文件。StreamReader.ReadLine() 提供了更多控制,但需要更仔细的资源管理。记住始终包含强大的错误处理,以便优雅地管理潜在的异常,例如文件未找到错误。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注