Saving files from the web

A few weeks ago I had to create an application which would download files from several SharePoint libraries. I had just done a similar thing for a Windows Phone 7 application, so I could reuse most of the code.

After running the application I received an awkward exception message which said: “This stream does not support seek operations”. This exception was triggered by the following code snippet:https://

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filelocationUrl);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
var stream = response.GetResponseStream();

I though this probably had something to do with it being a stream from a web so it can’t really check the size of a file. Lucky for me I wasn’t the first developer who had stumbled upon this issue. This blog post describes the same issue.

The code I was supposed to use is this:

Stream respStream = myResponse.GetResponseStream();
MemoryStream memStream = new MemoryStream();
byte[] buffer = new byte[2048];
int bytesRead = 0;
do
{
	bytesRead = respStream.Read(buffer, 0, buffer.Length);
	memStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
respStream.Close();
buffer = memStream.ToArray();
string html = System.Text.Encoding.ASCII.GetString(buffer);

Using this I’m specifying the size of the chunks which need to be downloaded. This code is something I had used in the past also, but after I saw how easy it was in an asynchronous environment (WP7 / Silverlight) I had hoped it would work in ASP.NET / SharePoint also.


Share