【问题标题】:Appending to MemoryStream附加到 MemoryStream
【发布时间】:2012-09-02 14:58:33
【问题描述】:

我正在尝试将一些数据附加到流中。这适用于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);
}

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

【问题讨论】:

  • 您能否解释一下为什么您不使用可扩展流进行两次写入?
  • 啊,这样吗?流 s2 = new MemoryStream(); // 可扩展容量内存流 s2.Write(existingData, 0, existingData.Length); WriteUnknownDataToStream(s2);
  • 是的,这就是我的意思......这就是为什么它是一个流而不是一个数组,不是吗?
  • @Rotem @ sprocketonline 你们中的某个人可能应该将其发布为答案。
  • 只需创建一个MemoryStream,将existingData 附加到该流,然后继续向其附加数据。

标签: c# arrays stream


【解决方案1】:

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

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

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

【讨论】:

  • 如果性能差异很重要,可以specify initial capacity of the stream。这样,如果您猜得好(或知道)最终大小,就不会重新分配。如果你猜错了,你会浪费内存或有影响性能的重新分配,但它仍然可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多