.net 了解克隆流的不同方法,以及在哪种情况下使用哪种方法

.net 了解克隆流的不同方法,以及在哪种情况下使用哪种方法,.net,stream,.net,Stream,复制文件流时,我遇到了两个示例: 这个, Using requestStream as IO.Stream = state.Request.EndGetRequestStream(ar) ' Copy the file contents to the request stream. Const bufferLength As Integer = 2048 Dim buffer(bufferLength - 1) As Byte Dim count As Integ

复制文件流时,我遇到了两个示例:

这个,

Using requestStream as IO.Stream = state.Request.EndGetRequestStream(ar)
    ' Copy the file contents to the request stream.
    Const bufferLength As Integer = 2048
    Dim buffer(bufferLength - 1) As Byte
    Dim count As Integer = 0
    Dim readBytes As Integer = 0
    Using stream As IO.FileStream = IO.File.OpenRead(state.FileName)
        While readBytes <> 0
            readBytes = stream.Read(buffer, 0, bufferLength)
            requestStream.Write(buffer, 0, readBytes)
            count += readBytes
        End While
    End Using
End Using
我的理解是,第一个将一个流直接复制到另一个流,第二个通过字节数组进行复制。两者都能起作用并达到同样的效果。我相信第一个会更快,但第二个看起来更简单,更容易维护等等

不过,我看不出您在第一个中设置了编码。为什么你需要用一个,而不是另一个

此外,对每个片段的赞成和反对意见进行客观的评论也会很有用。Thx

第二种方法不适用于任意二进制数据-它将数据视为UTF-8编码的文本数据,然后对其重新编码-这是一个非常糟糕的主意,除非您确实知道它是UTF-8编码的文本

第二种形式也使用字节数组,一次只使用一个缓冲区

然而,在第一个版本中有一个bug:当
bytesRead
为非零时,您将继续运行,但它以0开始

您可能需要:

Using stream As IO.FileStream = IO.File.OpenRead(state.FileName)
    readBytes = stream.Read(buffer, 0, bufferLength)
    While readBytes <> 0
        requestStream.Write(buffer, 0, readBytes)
        count += readBytes
        readBytes = stream.Read(buffer, 0, bufferLength)
    End While
End Using
但我不知道你是否能在VB中完成这样的复合赋值

其他一些选择:

  • 您可以使用以字节数组的形式读取整个文件,不过如果文件很大,显然会浪费内存。这是第二个代码的一种安全版本
  • 如果您使用的是.NET4,则可以使用。如果没有,您可以自己编写与扩展方法相同的代码,以便从其他项目中重用

您建议使用哪种缓冲区大小?(如果您不知道使用的典型文件大小)@Magnus:我通常使用8或16K。不要超过大约80K,否则缓冲区将在大对象堆上结束。@JonSkeet谢谢你,很好的评论和回答,我将使用你的示例,但是使用while循环,因为我对do循环有一种非理性的厌恶。@shoubs先生:实际上,我已经修改了代码来使用while循环——在编写do-while版本的过程中,我改变了主意;我不知道我为什么留着它。
Using stream As IO.FileStream = IO.File.OpenRead(state.FileName)
    readBytes = stream.Read(buffer, 0, bufferLength)
    While readBytes <> 0
        requestStream.Write(buffer, 0, readBytes)
        count += readBytes
        readBytes = stream.Read(buffer, 0, bufferLength)
    End While
End Using
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, bufferLength)) > 0)
{
    requestStream.Write(buffer, 0, readBytes);
    count += readBytes;
}