将一个流的内容复制到另一个流的最佳方法是什么?有标准的实用方法吗?


当前回答

简单安全-从原始来源制作新流:

    MemoryStream source = new MemoryStream(byteArray);
    MemoryStream copy = new MemoryStream(byteArray);

其他回答

MemoryStream有.WriteTo(outstream);

. net 4.0在普通流对象上有. copyto。

net 4.0:

instream.CopyTo(outstream);

简单安全-从原始来源制作新流:

    MemoryStream source = new MemoryStream(byteArray);
    MemoryStream copy = new MemoryStream(byteArray);

如果你想要一个过程复制一个流到其他的一个,尼克张贴是好的,但它是丢失的位置重置,它应该是

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    long TempPos = input.Position;
    while (true)    
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
    input.Position = TempPos;// or you make Position = 0 to set it at the start
}

但如果它在运行时不使用过程,则应该使用内存流

Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)    
{
    int read = input.Read (buffer, 0, buffer.Length);
    if (read <= 0)
        return;
    output.Write (buffer, 0, read);
 }
    input.Position = TempPos;// or you make Position = 0 to set it at the start

下面的代码可以解决这个问题,使用CopyTo将流复制到MemoryStream

Stream stream = new MemoryStream();

//任何需要输入流的函数。在我的情况下,保存PDF文件为流 document.Save(流);

MemoryStream newMs = (MemoryStream)stream;

byte[] getByte = newMs.ToArray();

//注意-请在finally块中处理流,而不是在using块中处理,因为它会抛出一个错误'访问被拒绝,因为流被关闭'

对于。net 3.5和尝试之前:

MemoryStream1.WriteTo(MemoryStream2);