FileStream.copyTo(Net.ConnectStream) what happens intern?

对着背影说爱祢 提交于 2019-12-13 15:31:28

问题


this code works fine. My question is what happens within the Net.ConnectionStream when i use the CopyTo() method?

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

More specific: What happens to the data?
1. write into the memory and upload then? (what's with big files?) 2. write into the network directly? (how does that work?)

Thanks for your answers


回答1:


It creates a byte[] buffer and calls Read on the source and Write on the destination until the source doesn't have anymore data.

So when doing this with big files you don't need to be concerned about running out of memory because you'll only allocate as much as the buffer size, 81920 bytes by default.

Here's the actual implementation -

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);
    }
}


来源:https://stackoverflow.com/questions/16341653/filestream-copytonet-connectstream-what-happens-intern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!