通过在流上执行操作,在' MemoryStream '包装后修改' byte[] '

本文关键字:包装 修改 byte MemoryStream 执行 操作 | 更新日期: 2023-09-27 18:08:23

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

我有一个主要使用byte[]而不是Stream的代码库,以及一个我想使用的作用于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的底层字节已经被修改。

通过在流上执行操作,在' MemoryStream '包装后修改' byte[] '

通过MemoStream(byte[])构造函数传入内存流的数组将用作后备缓冲区,并且确实反映更改。

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

也不要调用MemoryStream#GetBuffer(),因为这会抛出异常。只需使用- "记住" -原始数组,因为它代表'实时缓冲区数据'。

(原始数组的长度不能改变,因为数组具有不可变的大小;'相关数据的长度'可能需要以某种方式作为单独的值。