5

I've written following code to get the content from a web page and save to the system. if the webpage is in html format i'm able to save it. if the web page is in pdf format i'm unable to save it. After saving if i opend the file blank pages are coming.

I want to know How to save the pdf files from the response.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
webContent = reader.ReadToEnd();
StreamWriter sw = new StreamWriter(FileName);
sw.WriteLine(webContent);
sw.Close();

Please help me ASAP.

2 Answers 2

14

StreamReader.ReadToEnd() returns a string. PDF files are binary, and contain data that is not string-friendly. You need to read it into a byte array, and write the byte array to disk. Even better, use a smaller byte array as a buffer and read in small chunks.

You can also simplify the whole thing by just using webclient:

using (var wc = new System.Net.WebClient())
{
    wc.DownloadFile(Url, FileName);
}
2
  • PDF files are usually binary, aren't they? Since it is based upon PostScript it can be just text, also, I guess.
    – Uwe Keim
    Commented Jan 28, 2011 at 5:47
  • Fabulous method. :) +1 after a year. Commented Mar 14, 2012 at 14:16
6
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
WebResponse response = request.GetResponse();

using (Stream stream = response.GetResponseStream())
using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
    stream.BlockCopy(fs);
}

...
public static class StreamHelper
{
    public static void Copy(Stream source, Stream target, int blockSize)
    {
        int read;
        byte[] buffer = new byte[blockSize];
        while ((read = source.Read(buffer, 0, blockSize)) > 0)
        {
            target.Write(buffer, 0, read);
        }
    }
    public static void BlockCopy(this Stream source, Stream target, int blockSize = 65536)
    {
        Copy(source, target, blockSize);
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.