The example also fails to dispose the stream returned by the OpenRead method. Also, the example is sort of strange in that it employs an arbitrary UserAgent.
Here's a better example:
using (WebClient client = new WebClient ())
{
using (System.IO.Stream s = client.OpenRead(uri) )
{
byte[] bytes = s.ReadAllBytes();
// do your thing...
}
}
But that is a bit contrived. If you want to get all the bytes from a URI, you would use the WebClient.DownloadData() method, like so:
using (WebClient client = new WebClient ())
{
byte[] bytes = client.DownloadData(uri);
// do your thing...
}
}
Also be aware: The alternative contrived example code provided here employs an extension method, ReadAllBytes, on the Stream class, defined like so:
public static class Extensions
{
/// <summary>
/// Reads the contents of the stream into a byte array.
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <returns>A byte array containing the contents of the stream.</returns>
/// <exception cref="NotSupportedException">The stream does not support reading.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="System.IO.IOException">An I/O error occurs.</exception>
public static byte[] ReadAllBytes(this System.IO.Stream source)
{
long originalPosition = 0;
if (source.CanSeek)
{
originalPosition= source.Position;
source.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = source.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = source.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (source.CanSeek)
source.Position = originalPosition;
}
}
}
This extension is taken, slightly modified, from
http://www.lostechies.com/blogs/sdorman/archive/2009/01/10/reading-all-bytes-from-a-stream.aspx