简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM