Does anyone have sample code for streaming HTTP downloads from a single website directly for upload to a separate web server?

Background . I am trying to transfer an existing webpage to a separate web application using HttpWebRequest / HttpWebResponse in C #. One of the problems I hit is that I am trying to set the length of the contents of a file download request using the length of the file’s download content, HOWEVER, the problem is that the original webpage is on a web server for which HttpWebResponse do not specify the length of the content.

HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
 using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
 {
   var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
   uploadRequest.Method = "POST";
   uploadRequest.ContentLength = downloadResponse.ContentLength;  // ####

QUESTION . How can I update this approach to satisfy this case (when there is no set length for the content in the response to the download). Would it be possible to use a MemoryStream in some way? Any sample code would be appreciated. In particular, is there an example of code that someone will be shown how to perform a “downloaded” HTTP upload and download to avoid problems with the original web server that does not provide the length of the content?

thanks

+5
source share
1 answer

As I have already applied on the Microsoft forums, there are several options that you have.

However, so I would do it with MemoryStream:

HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;

byte [] buffer = new byte[4096];
using (MemoryStream ms = new MemoryStream())
using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
{
    Stream respStream = downloadResponse.GetResponseStream();
    int read = respStream.Read(buffer, 0, buffer.Length);

    while(read > 0)
    {
        ms.Write(buffer, 0, read);
        read = respStream.Read(buffer, 0, buffer.Length);
    }

    // get the data of the stream
    byte [] uploadData = ms.ToArray();

    var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
    uploadRequest.Method = "POST";
    uploadRequest.ContentLength = uploadData.Length;

    // you know what to do after this....
}

, ContentLength . , SendChunked true uploadRequest, . chunked, HttpWebRequest ( ) (, AllowWriteStreamBuffering true uploadRequest) .

+5

All Articles