3

I found this answer for Python. Does it apply to C# WebClient.OpenRead?

In the following example:

  1. Does OpenRead downloads all the csv file at once (hence ReadLine refers to a local Stream)?
  2. Like in Python, does the download is being done progressively with successive ReadLine?

Code sample

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://www.MyWebsite.com/FileToDownload.csv");
StreamReader csvFile= new StreamReader(stream);
while (!csvFile.EndOfStream)
{
    string line = csvFile.ReadLine();
    //do stuff with line
}
Community
  • 1
  • 1
Jax
  • 63
  • 8
  • 1
    don't you mean `new StreamReader(stream)` ? – user1859022 Feb 09 '17 at 19:26
  • Looking at the [source code](https://referencesource.microsoft.com/#System/net/System/Net/webclient.cs,ea41c9388029aa78,references), it seems that the response is downloaded in one go, although I'm not completely sure (thus only a comment). – Setsu Feb 09 '17 at 19:32
  • you are asking about OpenRead and csv file while your StreamReader use the csv file and not the WebClient. Can you please review again your question? – elirandav Feb 09 '17 at 19:35
  • My bad. I've corrected the code sample. – Jax Feb 09 '17 at 19:44

2 Answers2

2

It depends on the protocol, size of the download vs. buffer size and may even depend on the web server configuration. The implementation of HttpWebResponse, which is used internally, reads everything from a ConnectStream, which is capable of de-chunking transparently:

ConnectStream in reference source

Even in cases where decoding or decompressing is needed, streams are properly chained, so the implementation is clearly able to stream data without downloading everything locally up front.
But in practice the .NET http stack buffers as much as it can immediately, also when you're not reading a stream to end. These posts may be an interesting read:

To prove for your case, turn on Network Tracing, as HttpWebResponse will then dump information about connects, continuations, etc. Or use any other network sniffing tool. Be sure the file is large enough to see the effect.

Strictly speaking it will never be a "local stream", but the underlying buffer will hold more, if not all, of the requested file than you ask for in the first read.

Community
  • 1
  • 1
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
0

Judging from the documentation the HTTP GET request is sent as soon as you call OpenRead

Opens a readable stream for the data downloaded from a resource with the URI specified as a String.

user1859022
  • 2,585
  • 1
  • 21
  • 33