Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

17 Aug 2007

StreamHelper

The following is an example of a classic mistake for people that read from a Stream

Offcourse, if you look at the documentation for the Read method it clearly says that the function returns the number of bytes that were actually read. Here is a little helper function that keeps you from writing the same code over and over again

public void Copy(Stream input, Stream output, int bufferSize)
{
	byte[] buffer = new byte[bufferSize];
	int bytesRead;

	while((bytesRead = input.Read(buffer, 0, bufferSize)) > 0)
	{
		output.Write(buffer, 0, bytesRead);
	}
}

And as usual, a little demo of it’s use

static void DownloadFile(string url, string path)
{
	WebRequest req = WebRequest.Create(url);
	WebResponse rsp = req.GetResponse();
	using (Stream input = rsp.GetResponseStream())
	using (Stream output = File.Open(path, FileMode.Create))
	{
		StreamHelper.Copy(input, output, 1024 * 1000);
	}
}

static void Main(string[] args)
{
	DownloadFile("ftp://example.com/pub/test.bin", @"c:\test.bin");

	Console.Write("{0}Press any key to continue...", Environment.NewLine);
	Console.ReadKey();
}