c# - FileStream 在 128 字节后从 A 读取并写入 B C#

标签 c# filestream large-files

我有一个大文件(大约 400GB),我需要对其进行 FileStream 并将前 128 个字节跳过到另一个文件中。我有以下代码,但它不能正常工作,因为当我在流结束后检查文件大小时,文件 B 丢失了超过 128 个字节。我做错了什么?

private void SplitUnwantedHeader(string file1, string file2)
    {
        FileStream fr = new FileStream(file1, FileMode.Open, FileAccess.Read);
        FileStream fw = new FileStream(file2, FileMode.Create, FileAccess.Write);

        byte[] fByte = new byte[65534];
        long headerToSplit = 128;
        int bytesRead = 0;

        try
        {
            fr.Position = headerToSplit;
            do
            {
                bytesRead = fr.Read(fByte, 0, fByte.Length);
                fw.Write(fByte, 0, fByte.Length - (int)headerToSplit);
            } while (bytesRead != 0);
        }
        catch (Exception ex)
        {
            UpdateStatusBarMessage.ShowStatusMessage(ex.Message);
        }
        finally
        {
            fw.Close();
            fr.Close();
        }
    }

谢谢。

最佳答案

线

 fw.Write(fByte, 0, fByte.Length - (int)headerToSplit);

在这样的循环中使用时是错误的。它将在每个循环周期写入“缓冲​​区大小”减去 128 字节。相反,代码应该在复制期间写入 bytesRead 计数。

 fw.Write(fByte, 0, bytesRead);

仅在 进入 copy-everything-else 循环之前执行偏移量。此外,循环可以替换为 FileStream.CopyTo (自 .NET 4 起)和 using可以整理资源管理。

也就是说,考虑:

using (var fr = new FileStream(file1, FileMode.Open, FileAccess.Read))
using (var fw = new FileStream(file2, FileMode.Create, FileAccess.Write)) {
    fr.Position = 128; // or fr.Seek(128, SeekOrigin.Begin);
    fr.CopyTo(fw, 65534);
}

关于c# - FileStream 在 128 字节后从 A 读取并写入 B C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339720/

相关文章:

c# - WebAPI 序列化程序序列化基类而不是笨拙的子类

c# - Azure 中继混合连接 - 如何发送同步请求/响应

c# - Filestream.write 不起作用

mysql - 程序打开大型MySQL转储

c# - 调用 .SubmitChanges() linq 时获取随机堆栈溢出

c# - 使用 div 显示错误

c++ - 每次运行时文件中的连续输出

vb.net - 从流生成字节数组

csv - 如何从 compojure API 流式传输大型 CSV 响应,以便整个响应不会立即保存在内存中?

c++ - 外籍解析器 : memory consumption