FileStream.copyTo(Net.ConnectStream)实习生会发生什么?

zir*_*bel 2 c# connection stream filestream

此代码可以正常工作。我的问题是,当我使用CopyTo()方法时,Net.ConnectionStream中会发生什么?

System.Net.HttpWebRequest request 
using (FileStream fileStream = new FileStream("C:\\myfile.txt")
{                        
    using (Stream str = request.GetRequestStream())
    {                   
         fileStream.CopyTo(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

更具体地说:数据发生了什么?
1.写入内存然后上传?(大文件用什么?)2.直接写入网络?(这是如何运作的?)

谢谢你的回答

Bra*_*uff 5

它创建一个byte[]缓冲区并Read在源和Write目标上调用,直到源不再有数据为止。

因此,对大文件执行此操作时,您不必担心内存不足,因为您只会分配与缓冲区大小一样多的内存,默认情况下为81920字节。

这是实际的实现-

public void CopyTo(Stream destination)
{
    // ... a bunch of argument validation stuff (omitted)
    this.InternalCopyTo(destination, 81920);
}

private void InternalCopyTo(Stream destination, int bufferSize)
{
    byte[] array = new byte[bufferSize];
    int count;
    while ((count = this.Read(array, 0, array.Length)) != 0)
    {
        destination.Write(array, 0, count);
    }
}
Run Code Online (Sandbox Code Playgroud)