C# 文件读取

        文件读取是指使用 C# 程序从计算机文件系统中获取文件内容的过程。将存储在磁盘上的文件内容加载到内存中,供程序处理。主要类型有:文本文件读取(如 .txt, .csv, .json, .xml);二进制文件读取(如 .jpg, .png, .exe)。

同步方法

File 

ReadAllText

是 C# 中一个简单易用的文件写入方法,它会创建新文件,如果文件已存在则覆盖。

string path = @"D:\CSharpProject\File\MyTest.txt";
string str = File.ReadAllText(path);

 ReadLines

获取文件中每行数据组成的集合

string path = @"D:\CSharpProject\File\MyTest.txt";
var list = File.ReadLines(path).ToList();
Console.WriteLine(string.Join(",", list));

ReadAllLines

会一次性将整个文本文件的所有行读取到一个字符串数组中。

string path = @"D:\CSharpProject\File\MyTest.txt";
string[] list = File.ReadAllLines(path);
Console.WriteLine(string.Join(",", list));

ReadAllBytes

一个用于读取二进制文件的方法,它会将整个文件内容读取到一个字节数组中。

string path = @"D:\CSharpProject\File\MyTest.txt";
byte[] str = File.ReadAllBytes(path);

StreamReader

StreamReader 是 System.IO 命名空间中的一个类,专门用于从流(如文件流)中读取字符数据。它提供了高效的文本读取能力,特别适合处理大型文本文件。

方法描述
Read()读取下一个字符
ReadLine()读取一行字符
ReadToEnd()读取从当前位置到流末尾的所有内容

简单使用

string path = @"D:\CSharpProject\File\MyTest.txt";
using (StreamReader reader = new StreamReader(path))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}

逐行读取

using (StreamReader reader = new StreamReader("data.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

读取特定数量字符

char[] buffer = new char[100];
using (StreamReader reader = new StreamReader("file.txt"))
{
    int charsRead = reader.Read(buffer, 0, buffer.Length);
    string result = new string(buffer, 0, charsRead);
}

FileStream 

         FileStream 是 System.IO 命名空间中的一个类,提供了对文件进行低级读写操作的能力。与更高级的 StreamReader/StreamWriter 相比,FileStream 提供了更底层的控制,适合处理二进制文件或需要精细控制文件操作的场景。

using System.IO;

string filePath = "example.bin";

// 使用 using 语句确保资源被正确释放
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    byte[] buffer = new byte[fileStream.Length];
    int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
    
    Console.WriteLine($"读取了 {bytesRead} 字节");
    // 处理 buffer 中的数据...
}

异步方法

File 

ReadAllTextAsync

是ReadAllText的异步实现,功能相同,不会阻塞主线程。

using System.IO;
using System.Threading.Tasks;

public async Task<string> ReadFileContentAsync(string filePath)
{
    return await File.ReadAllTextAsync(filePath);
}

ReadAllLinesAsync

是ReadAllLines的异步实现,功能相同,不会阻塞主线程。

using System.IO;
using System.Threading.Tasks;

public async Task<string[]> ReadFileAsync(string filePath)
{
    return await File.ReadAllLinesAsync(filePath);
}

ReadAllBytesAsync

是ReadAllBytes的异步实现,功能相同,不会阻塞主线程

using System.IO;
using System.Threading.Tasks;

public async Task<byte[]> ReadBinaryFileAsync(string filePath)
{
    return await File.ReadAllBytesAsync(filePath);
}

StreamReader

 简单使用

using System.IO;
using System.Threading.Tasks;

async Task<string> ReadFileAllTextAsync(string filePath)
{
    using (StreamReader reader = new StreamReader(filePath))
    {
        return await reader.ReadToEndAsync();
    }
}

异步逐行读取文件

using (StreamReader reader = new StreamReader("data.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

异步读取指定数量字符

async Task<string> ReadChunkAsync(string path, int chunkSize)
{
    using (var reader = new StreamReader(path))
    {
        char[] buffer = new char[chunkSize];
        int bytesRead = await reader.ReadBlockAsync(buffer, 0, chunkSize);
        return new string(buffer, 0, bytesRead);
    }
}

FileStream 

using System.IO;
using System.Threading.Tasks;

async Task<byte[]> ReadFileFullyAsync(string filePath)
{
    using (FileStream fs = new FileStream(
        filePath, 
        FileMode.Open, 
        FileAccess.Read, 
        FileShare.Read, 
        bufferSize: 4096, 
        FileOptions.Asynchronous)) // 关键选项
    {
        byte[] buffer = new byte[fs.Length];
        await fs.ReadAsync(buffer, 0, buffer.Length);
        return buffer;
    }
}

对比

方法特点适用场景内存效率异步支持典型文件大小
File.ReadAllText一次性读取全部文本小文本文件处理<10MB
File.ReadAllTextAsync异步读取全部文本UI应用读取小文本<10MB
File.ReadAllLines按行读取为数组需要行处理的小文件<10MB
File.ReadAllLinesAsync异步按行读取UI应用需要行处理<10MB
File.ReadAllBytes读取二进制数据图片/音频等二进制文件<50MB
File.ReadAllBytesAsync异步读取二进制UI应用处理二进制<50MB
File.ReadLines延迟行迭代大文本文件处理10MB+
StreamReader灵活文本读取需要控制读取过程有(Async方法)任意大小
FileStream底层二进制读取大文件/随机访问任意大小

选择参考

参考项

推荐方法

场景举例

小文本文件处理 ( < 1MB )

ReadAllText 

ReadAllTextAsync

ReadAllLines 

ReadAllLinesAsync

配置文件读取

小型JSON/XML文件解析

模板文件加载

大文本文件处理 ( > 10MB )

File.ReadLines (LINQ兼容)

StreamReader (逐行处理)

StreamReader.ReadLineAsync (异步逐行)

日志文件分析

大型CSV数据处理

文本文件实时监控

二进制文件处理

File.ReadAllBytes / ReadAllBytesAsync (小文件)

FileStream (大文件)

图片/音视频处理

文件加密/解密

自定义二进制格式解析

同步和异步选择

  1. 使用同步方法

    • 简单的控制台应用程序

    • 需要简单快速完成的小文件操作

    • 在后台线程中执行的文件操作

  2. 使用异步方法

    • UI应用程序(避免界面冻结)

    • Web应用程序和服务(提高并发处理能力)

    • 大文件操作(避免阻塞主线程)

    • 需要响应性的应用程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值