在 C# 中,如果要读取超大的文本文件,可以使用逐行读取或分块读取的方式,以避免一次性将整个文件加载到内存中。

逐行读取文本文件

逐行读取文本文件的示例代码如下:

using System;
using System.IO;

string filePath = 'path/to/file.txt';

try
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            // 处理每一行的逻辑
            Console.WriteLine(line);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine('读取文件时发生错误: ' + ex.Message);
}

上述代码通过使用 StreamReader 类逐行读取文本文件,并在每次循环中处理每一行的数据。这种方法适用于处理超大文本文件,因为它只会在每次读取一行时才将数据加载到内存中,而不是一次性加载整个文件。

分块读取文本文件

另一种方式是使用分块读取的方式,通过设置一个缓冲区来一次读取一定数量的字符。示例代码如下:

using System;
using System.IO;

string filePath = 'path/to/file.txt';
int bufferSize = 4096;

try
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        char[] buffer = new char[bufferSize];
        int bytesRead;
        while ((bytesRead = sr.Read(buffer, 0, bufferSize)) > 0)
        {
            // 处理读取的数据
            string data = new string(buffer, 0, bytesRead);
            Console.WriteLine(data);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine('读取文件时发生错误: ' + ex.Message);
}

上述代码使用 StreamReader 类的 Read() 方法来一次读取指定大小的字符块,并将其转换为字符串进行处理。通过适当调整缓冲区的大小,你可以平衡内存占用和读取性能。

无论使用逐行读取还是分块读取的方式,都可以有效地处理超大文本文件,而不会造成内存溢出的问题。

C# 读取超大文本文件:逐行读取与分块读取

原文地址: https://www.cveoy.top/t/topic/ptj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录