I’ve started using a WebRequest to retrieve a file from a given URL. If I hit the URL in a browser I just get prompted to download the file. I’d like to take this file and redirect it to another URL.
I’ve got the basics working but I’m not intimate with streaming and HTTP so I’m a bit lost. I know that the following code doesn’t work because the written file also includes all the extra http responses as well and the file then ends up corrupt on the other side (in this case it’s a PDF file):
var toRequest = WebRequest.Create(destinationUrl);
toRequest.Method = "PUT";
toRequest.UseDefaultCredentials = true;
toRequest.ContentType = "application/octet-stream";
var fromRequest = WebRequest.Create(reportUrl);
fromRequest.UseDefaultCredentials = true;
fromRequest.Method = "GET";
fromRequest.ContentType = "application/octet-stream";
var buffer = new byte[10240];
int bytesRead = 0;
int totalBytesRead = 0;
Stream responseStream;
do
{
responseStream = fromRequest.GetResponse().GetResponseStream();
if (responseStream != null)
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
logger.Info(String.Format("Read {0} bytes", bytesRead));
}
totalBytesRead += bytesRead;
} while (bytesRead > 0);
toRequest.ContentLength = totalBytesRead;
var writer = new BinaryWriter(toRequest.GetRequestStream());
writer.Write(buffer, 0, totalBytesRead);
HttpWebResponse response = (HttpWebResponse)toRequest.GetResponse();
response.Close();
if (responseStream != null) responseStream.Close();
writer.Close();
In my test scenario the “reportUrl” is a SSRS generated PDF file. Again, hitting this link directly in a browser just results in being prompted to save the file to my machine. I want my code to take this file and redirect it to the “destinationUrl”, which would be something like “http://testserver/folder/report.pdf”.
Again, the basics work, but the “report.pdf” file is corrupt and won’t load as it currently contains the extra SSRS generated metadata:
1 >>
endobj
7 0 obj
<< /Type /Catalog /Pages 6 0 R >>
endobj
8 0 obj
<< /Title <feff004300680061006e0067006500470075006900640065>
/Author <>
/Subject <>
/Creator (Microsoft Reporting Services 10.0.0.0)
/Producer (Microsoft Reporting Services PDF Rendering Extension 10.0.0.0)
/CreationDate (D:20120221083306-07'00')
>>
So, is the WebRequest object even the correct way to do this? Would there be a smarter way that would give me easier access to the file?
Thanks!
Use a WebClient to download the PDF directly.
http://www.csharp-examples.net/download-files/