views:

72

answers:

1

Hi,

How can I download a pdf and store to disk using vb.net or c#?

The url (of the pdf) has some rediection going on before the final pdf is reached.

I tried the below but the pdf seems corrupted when I attempt to open locally,

Dim PdfFile As FileStream = File.OpenWrite(saveTo)
Dim PdfStream As MemoryStream = GetFileStream(pdfURL)
PdfStream.WriteTo(PdfFile)
PdfStream.Flush()
PdfStream.Close()
PdfFile.Flush()
PdfFile.Close()

many thanks,

KS

+1  A: 

You can try to use the WebClient (System.Net namespace) class to do this which will avoid any stream work on your side.

The following C# code grabs an IRS form and saves it to C:\Temp.pdf.

using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", @"C:\Temp.pdf");
}
Pat
Tried that, opening pdf I get...."Adobe Reader could not open file because it is either not a supported file type or because the file has been damaged blah blah"
Perplexed
GetFileStream function:Protected Function GetFileStream(ByVal URL As String) As MemoryStream Dim _url As String = URL Dim _wb As WebClient = New WebClient Dim myBuffer() As Byte Dim _str As MemoryStream = Nothing Try myBuffer = _wb.DownloadData(_url) _str = New MemoryStream(myBuffer) Catch ex As Exception _str = Nothing End Try Return _strEnd Function
Perplexed