MemoryStream.WriteTo(流destinationStream)与Stream.CopyTo(流destinationStream)WriteTo、MemoryStream、desti

2023-09-03 16:44:30 作者:在成长中疼痛过的人

哪个更好: MemoryStream.WriteTo(流destinationStream) Stream.CopyTo(流destinationStream)? ?

我说的这两种方式没有缓冲,因为我在做这样的比较:

I am talking about the comparison of these two methods without Buffer as I am doing like this :

Stream str = File.Open("SomeFile.file");
MemoryStream mstr = new MemoryStream(File.ReadAllBytes("SomeFile.file"));

using(var Ms = File.Create("NewFile.file", 8 * 1024))
{
    str.CopyTo(Ms) or mstr.WriteTo(Ms);// Which one will be better??
}

更新

下面是我想要做的:

Update

Here is what I want to Do :

开启文件[说的X型文件] 解析内容 从这里我得到了新的流捆绑[3〜4档] 解析一个流 在提取成千上万的文件[流是一个图像文件] 保存其他流文件 编辑的所有文件 在生成新的X类型文件。

我已经写了code这实际上是正常工作的每一位。

I have written every bit of code which is actually working correctly..

但现在我优化了code键使最高效的。

But Now I am optimizing the code to make the most efficient.

推荐答案

这是一种历史的偶然,有两种方法可以做到同样的事情。 MemoryStream的总是有的writeTo()方法,流没有获得CopyTo从()方法,直到.NET 4。

It is an historical accident that there are two ways to do the same thing. MemoryStream always had the WriteTo() method, Stream didn't acquire the CopyTo() method until .NET 4.

在MemoryStream.WriteTo()的版本是这样的:

The MemoryStream.WriteTo() version looks like this:

public virtual void WriteTo(Stream stream)
{
    // Exception throwing code elided...
    stream.Write(this._buffer, this._origin, this._length - this._origin);
}

在Stream.CopyTo()实现是这样的:

The Stream.CopyTo() implementation like this:

private void InternalCopyTo(Stream destination, int bufferSize)
{
    int num;
    byte[] buffer = new byte[bufferSize];
    while ((num = this.Read(buffer, 0, buffer.Length)) != 0)
    {
        destination.Write(buffer, 0, num);
    }
}

Stream.CopyTo()是比较普遍的,它可以用于任何流。并帮助了摸索,比如说,从一个的NetworkStream复制数据的程序员。忘记从读注意返回值()是的非常的常见错误。但是,它当然副本的字节数的两倍,并分配了临时缓存,MemoryStream的并不需要它,因为它可以从它自己的缓冲区直接写。所以你还是preFER的writeTo()。注意到不同的是不太可能。

Stream.CopyTo() is more universal, it works for any stream. And helps programmers that fumble copying data from, say, a NetworkStream. Forgetting to pay attention to the return value from Read() was a very common bug. But it of course copies the bytes twice and allocates that temporary buffer, MemoryStream doesn't need it since it can write directly from its own buffer. So you'd still prefer WriteTo(). Noticing the difference isn't very likely.