通过对流执行操作来修改被 MemoryStream 包装后的 byte[]?

Modify a `byte[]` after it has been wrapped by a `MemoryStream` by performing actions on the stream?

是否可以在 byte[]MemoryStream 包装后通过对流执行操作来修改它?

我有一个主要使用 byte[] 而不是 Stream 的代码库,以及我想使用的第 3 方方法,该方法作用于 Stream.

我试过一个示例解决方案,使用如下代码,我们看到 originalBytes 变量没有被修改,尽管流显然已经被修改。

using System;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        const string filePath = "C:\new text document.txt";

        var originalBytes = File.ReadAllBytes(filePath);

        var stream = new MemoryStream(originalBytes);

        stream.SetLength(1);

        var modifiedBytes = stream.ToArray();

        Console.WriteLine(originalBytes.Length == modifiedBytes.Length);

        Console.ReadLine();
    }
}

有没有一种方法可以将 byte[]MemoryStream 相关联,使得对流的修改也会对数组产生影响?

在此解决方案中做出的决定让我束手无策,这意味着我没有重构解决方案以在代码库周围更频繁地使用流的简单选择。


编辑: 我现在看到我的代码片段不正确。更好地表示这将是一些简单的东西

static void Main(string[] args)
{
    const string filePath = "C:\new text document.txt";

    var originalBytes = File.ReadAllBytes(filePath);

    var stream = new MemoryStream(originalBytes);

    var streamWriter = new StreamWriter(stream);
    streamWriter.Write("54321");
    streamWriter.Flush();

    var modifiedBytes = stream.ToArray();

    for (int i = 0; i < originalBytes.Length; i++)
    {
        Console.WriteLine(originalBytes[i] == modifiedBytes[i]);
    }

    Console.ReadLine();
}

虽然很粗糙,但确实给出了一些指示,表明修改后的字节和原始字节实际上是相互代表的,因此 originalBytes 的底层字节已被修改。

通过 MemoStream(byte[]) constructor 传递到内存流中的数组将 用作后备缓冲区,它 确实 反映变化。

在此处不要调用MemoryStream#ToArray(),它总是会创建一个new数组。该数组的长度取决于内存流中实际存在的数据量(由 SetLength 写入或调整),与内部缓冲区大小无关。如图所示,这可能小于最初提供的数组长度。

也不要调用MemoryStream#GetBuffer(),因为那样会抛出异常。只需使用 - "remember" - 原始数组,因为它代表 'live buffer data'.

(原数组的长度不能改变,因为数组的大小是不可变的;'length of relevant data'可能需要以某种方式作为单独的值携带。)