上一篇
在C#开发中,处理大文件是一个常见但又容易出错的任务。如果一次性将整个大文件加载到内存中,很容易导致内存溢出(OutOfMemoryException)。这时,FileStream 就派上用场了!它允许我们以“流”的方式逐块读写文件,既节省内存又提高效率。
FileStream 是 .NET 中用于对文件进行字节级读写操作的类。它继承自 Stream 类,支持同步和异步操作,非常适合处理大文件。
下面是一个典型的分块读取大文件的示例。我们每次只读取 4KB(4096 字节),这样即使处理几个 GB 的文件也不会占用太多内存。
using System;using System.IO;public class LargeFileReader{ public static void ReadLargeFile(string filePath) { const int bufferSize = 4096; // 每次读取4KB byte[] buffer = new byte[bufferSize]; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { // 处理读取到的数据(例如写入另一个文件、计算哈希等) // 这里仅作演示,可替换为实际逻辑 Console.WriteLine($"已读取 {bytesRead} 字节"); } } }} 写入大文件同样推荐分块操作。下面示例展示如何将大量数据分批写入目标文件:
using System;using System.IO;public class LargeFileWriter{ public static void WriteLargeFile(string outputPath, long totalSize) { const int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; // 填充缓冲区(例如全为0) for (int i = 0; i < bufferSize; i++) buffer[i] = 0; using (FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { long bytesWritten = 0; while (bytesWritten < totalSize) { int toWrite = (int)Math.Min(bufferSize, totalSize - bytesWritten); fs.Write(buffer, 0, toWrite); bytesWritten += toWrite; } } Console.WriteLine($"已成功写入 {totalSize} 字节到 {outputPath}"); }} using 语句:确保 FileStream 在使用后自动释放资源,避免文件句柄泄露。ReadAsync / WriteAsync 避免阻塞主线程。IOException、UnauthorizedAccessException 等常见异常。通过本文,你已经掌握了如何使用 C# FileStream 安全高效地读写大文件。无论是日志分析、数据迁移还是多媒体处理,这种流式操作都是处理大文件的黄金标准。记住关键词:C# FileStream、大文件读写、C#文件流操作 和 高效读取大文件,它们将帮助你在实际项目中快速定位解决方案。
现在,你可以自信地处理任何规模的文件了!
本文由主机测评网于2025-12-13发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127348.html