【问题标题】:Inconsistent file size change while writing bytes from stream to a file将字节从流写入文件时文件大小更改不一致
【发布时间】:2013-12-11 10:15:23
【问题描述】:

我有一个大小为 10124 的文件,我正在添加一个字节数组,文件开头的长度为 4。 之后文件大小应变为 10128,但当我将其写入文件时,大小减少到 22 个字节。不知道问题出在哪里

public void AppendAllBytes(string path, byte[] bytes)
{
    var encryptedFile = new FileStream(path, FileMode.Open, FileAccess.Read);
    ////argument-checking here.
    Stream header = new MemoryStream(bytes);

    var result = new MemoryStream();
    header.CopyTo(result);
    encryptedFile.CopyTo(result);

    using (var writer = new StreamWriter(@"C:\\Users\\life.monkey\\Desktop\\B\\New folder (2)\\aaaaaaaaaaaaaaaaaaaaaaaaaaa.docx.aef"))
    {
        writer.Write(result);
    }
}

如何将字节写入文件?

【问题讨论】:

  • 不要使用StreamWriter写入二进制数据。

标签: c# stream binarystream


【解决方案1】:

问题似乎是由以下原因引起的:

  • 使用StreamWriter 写入二进制格式的数据。名称并没有直观地暗示这一点,但 StreamWriter 类适合编写文本数据。

  • 传递整个流而不是实际的二进制数据。要获取存储在MemoryStream 中的字节,请使用其方便的ToArray() 方法。

我建议你使用以下代码:

public void AppendAllBytes(string path, byte[] bytes)
{
    var fileName = @"C:\\Users\\life.monkey\\Desktop\\B\\New folder (2)\\aaaaaaaaaaaaaaaaaaaaaaaaaaa.docx.aef";

    using (var encryptedFile = new FileStream(path, FileMode.Open, FileAccess.Read))
    using (var writer = new BinaryWriter(File.Open(fileName, FileMode.Append)))
    using (var result = new MemoryStream())
    {
        encryptedFile.CopyTo(result);
        result.Flush(); // ensure header is entirely written.

        // write header directly, no need to put it in a memory stream
        writer.Write(bytes);
        writer.Flush(); // ensure the header is written to the result stream.
        writer.Write(result.ToArray());
        writer.Flush(); // ensure the encryptdFile is written to the result stream.
    }
}

上面的代码使用了更适合二进制数据的BinaryWriter 类。它有一个Write(byte[] bytes) 方法重载,用于将整个数组写入文件。代码使用对 Flush() 方法的常规调用,有些人可能认为不需要,但这些通常保证在调用 Flush() 方法之前写入的所有数据都保留在流中。

【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2015-06-23
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多