WebRequest request = WebRequest.Create(someUrl); using(WebResponse response = request.GetResponse()) { using(StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); } }
Unfortunately, StreamReader is only good for reading text. When it comes to binary data the result has a good chance of being incomplete. The approach for binary data is to stick to the basic Stream type and read raw bytes.
byte[] result; byte[] buffer = new byte[4096]; WebRequest wr = WebRequest.Create(someUrl); using(WebResponse response = wr.GetResponse()) { using(Stream responseStream = response.GetResponseStream()) { using(MemoryStream memoryStream = new MemoryStream()) { int count = 0; do { count = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); } while(count != 0); result = memoryStream.ToArray(); } } }
P.S. IDisposable lurks everywhere!. It’s a shame some classes use an explicit interface implementation and hide the Dispose method from Intellisense.
P.P.S. Commercials are the best things going on Monday Night Football these days. Except the commercials for other ABC shows. I don't know why I turn on television.