gpt4 book ai didi

c# - 附加到 MemoryStream

转载 作者:太空狗 更新时间:2023-10-29 19:50:45 24 4
gpt4 key购买 nike

我正在尝试将一些数据附加到流中。这适用于 FileStream,但不适用于 MemoryStream,因为缓冲区大小是固定的。

将数据写入流的方法与创建流的方法分开(我在下面的示例中大大简化了它)。创建流的方法不知道要写入流的数据长度。

public void Foo(){
byte[] existingData = System.Text.Encoding.UTF8.GetBytes("foo");
Stream s1 = new FileStream("someFile.txt", FileMode.Append, FileAccess.Write, FileShare.Read);
s1.Write(existingData, 0, existingData.Length);


Stream s2 = new MemoryStream(existingData, 0, existingData.Length, true);
s2.Seek(0, SeekOrigin.End); //move to end of the stream for appending

WriteUnknownDataToStream(s1);
WriteUnknownDataToStream(s2); // NotSupportedException is thrown as the MemoryStream is not expandable
}

public static void WriteUnknownDataToStream(Stream s)
{
// this is some example data for this SO query - the real data is generated elsewhere and is of a variable, and often large, size.
byte[] newBytesToWrite = System.Text.Encoding.UTF8.GetBytes("bar"); // the length of this is not known before the stream is created.
s.Write(newBytesToWrite, 0, newBytesToWrite.Length);
}

我的想法是将可扩展的 MemoryStream 发送到该函数,然后将返回的数据附加到现有数据。

public void ModifiedFoo()
{
byte[] existingData = System.Text.Encoding.UTF8.GetBytes("foo");
Stream s2 = new MemoryStream(); // expandable capacity memory stream

WriteUnknownDataToStream(s2);

// append the data which has been written into s2 to the existingData
byte[] buffer = new byte[existingData.Length + s2.Length];
Buffer.BlockCopy(existingData, 0, buffer, 0, existingData.Length);
Stream merger = new MemoryStream(buffer, true);
merger.Seek(existingData.Length, SeekOrigin.Begin);
s2.CopyTo(merger);
}

有更好(更有效)的解决方案吗?

最佳答案

一个可能的解决方案是首先不限制 MemoryStream 的容量。如果您事先不知道需要写入的总字节数,请创建一个未指定容量的 MemoryStream 并将其用于两次写入。

byte[] existingData = System.Text.Encoding.UTF8.GetBytes("foo");
MemoryStream ms = new MemoryStream();
ms.Write(existingData, 0, existingData.Length);
WriteUnknownData(ms);

这无疑比从 byte[] 初始化 MemoryStream 性能要差,但如果您需要继续写入流,我相信这是您唯一的选择选项。

关于c# - 附加到 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com