views:

43

answers:

1

Hi,

In C# rather than having to dowloading a file from the web using httpwebrequest, save this to file somewhere, and then upload to a webservice using a POST with the file as one of the parameters...

Can I instead somehow open a reader stream from httpwebresponse and then stream this into the http POST? Any code someone could post to show how?

In other words I'm trying to avoid haing to save to disk first.

Thanks

+2  A: 

Something like that should do the trick :

HttpWebRequest downloadRequest = WebRequest.Create(downloadUri) as HttpWebRequest;
using(HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
    HttpWebRequest uploadRequest = new HttpWebRequest(uploadUri);
    uploadRequest.Method = "POST";
    uploadRequest.ContentLength = downloadResponse.ContentLength;
    using (Stream downloadStream = downloadResponse.GetResponseStream())
    using (Stream uploadStream = uploadRequest.GetRequestStream())
    {
        byte[] buffer = new byte[4096];
     int totalBytes = 0;
     while(totalBytes < downloadResponse.ContentLength)
     {
      int nBytes = downloadStream.Read(buffer, 0, buffer.Length);
      uploadStream.Write(buffer, 0, nBytes);
      totalBytes += nRead;
     }
    }
    HttpWebResponse uploadResponse = uploadRequest.GetResponse() as HttpWebResponse;
    uploadResponse.Close();
}

(untested code)

Thomas Levesque
Wow...I'll try it out when I'm back home and then update...thanks very much
Greg
Hey Thomas - just getting back to this - I'm noting I have an issue if I'm targetting a page for which the server isn't providing a ContentLength (e.g. at downloadResponse.ContentLength). I seem to get "System.NotSupportedException: This stream does not support seek operations..". Any ideas here in terms of how to address this?
Greg
On which instruction do you get this exception ?
Thomas Levesque