Is System.Net.WebClient.DownloadFile() reading the downloaded file in chunks?
Is System.Net.WebClient.DownloadFile() reading the downloaded file in chunks, or is it reading the whole file to memory, to dump it to disk in the end? Does anybody know? From my tests it seems that the file is created with 0 bytes rightaway and then explodes to full size once the download has finished. Bu开发者_如何转开发t somehow this is so hard to believe because it would mean that 2GB of RAM are occupied when downloading a 2GB file...that would be pointless.
It writes whatever is received directly to a FileStream. DownloadBitsState.RetrieveBytes() method, WriteStream.Write() call if you want to take a look with Reflector or the Reference Source. The size property doesn't get updated in Explorer until the file is closed.
By looking at the disassembled code (assembly System, Version=4.0.0.0), I found the following: the method DownloadFile() calls the method DownloadBits() with parameter asyncOp = null to download the file. When the download is completed, the method returns the whole downloaded file as byte[]. Hence, the memory is wasted and one could run into problems with large files.
The Web response is streamed directly into the file; it doesn't buffer the whole thing to memory. The method blocks the thread until the whole file is downloaded. You can use DownloadFileAsync()
to download it asynchronously.
精彩评论