0
当复制一个文件流,我遇到了两个例子:了解不同的方法,并且情况下使用这
这一个,
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
这一个:
'Copy the contents of the file to the request stream.
Dim fileContents As Byte()
Using fileStream As New IO.StreamReader(state.FileName)
fileContents = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
End Using
Using requestStream As IO.Stream = state.Request.EndGetRequestStream(ar)
requestStream.Write(fileContents, 0, fileContents.Length)
End Using
我理解的是第一个拷贝一个流直接到另一个,通过一个字节数组的第二副本。两者都工作并实现相同的目的。我相信第一个会更快,但第二个看起来更简单,更容易维护等。
我看不到你在第一个中设置编码的位置。你为什么需要一个人做,而不是另一个呢?
此外,对每个片段的pro和con的客观评论将是有用的。 THX
你会推荐什么样的缓冲区大小? (如果你不知道使用的典型文件大小) – Magnus
@Magnus:我通常使用8或16K。不要超过80K,否则缓冲区将会在大对象堆上结束。 –
@JonSkeet谢谢你,很好的评论和回答,我会用你的例子,但有一个while循环,因为我有一个无理的厌恶做循环。 –