【问题标题】:FileStream.Read not reading last 'chunk'FileStream.Read 没有读取最后一个“块”
【发布时间】:2015-03-03 08:06:31
【问题描述】:

我有一个有趣的场景,希望其他人偶然发现。我正在尝试将打开的 FileStream 的一部分复制到 c# .Net 3.5 中的单独文件流。使用下面的代码,我读取了 37 个 4096 字节的“块”,但 未能读取最后一个 3812 字节的“部分块”。

string filPath = "c:\aRatherSmallFileThatCouldBeQuiteLarge.log";
string tmpNam = Path.GetTempFileName();
using (FileStream wt = new FileStream(tmpNam, FileMode.Open, FileAccess.Write))
{
    using (FileStream rd = new FileStream(filPath, FileMode.Open, FileAccess.Read))
    {
        long cutPosition = 65217;
        int bytesRead;
        int chunkSize = 4096;
        byte[] buffer = new byte[chunkSize];
        while ((bytesRead = rd.Read(buffer, 0, chunkSize)) != 0)
            wt.Write(buffer, 0, bytesRead);
    }
    File.Copy(tmpNam, filPath, true);
}
File.Delete(tmpNam);

没有产生错误;最后的 3812 字节根本没有按预期写入目标文件。

这是一个小例子,但我打算在非常大的文件上使用它......所以将源文件读入内存的解决方案在这里不可行。

【问题讨论】:

    标签: .net-3.5 filestream


    【解决方案1】:

    我认为您需要将 File.Copy 移到 using 块之外:

    using (FileStream wt = new FileStream(tmpNam, FileMode.Open, FileAccess.Write))
    {
        using (FileStream rd = new FileStream(filPath, FileMode.Open, FileAccess.Read))
        {
            ...
        } // closes the read stream
        // you're trying to move the file here, before the write stream is flushed out
    } // closes the write stream (flushing out the last chunk)
    // Do the copy after the write stream has been flushed and closed
    File.Copy(tmpNam, filPath, true);
    File.Delete(tmpNam);
    

    您可能会在最终写入刷新到临时文件之前复制文件。

    【讨论】:

    • 感谢@Cory,但这些只是为了传达代码的意图。目前我只是打开 tmp 文件并观察它是不完整的。
    • 你在用cutPosition做一些我们在上面的例子中看不到的事情吗?你在这里不用它。
    • 不,实际上您的第一条评论非常正确。在写入流关闭之前,我正在打破一条线......因此在它最终刷新之前。非常感谢。已接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2021-04-02
    相关资源
    最近更新 更多