'How do I download a PDF file using a URL link to local computer in c#
I'm trying to download a pdf file using a URL link to my computer, but it gives the following error:
'Unable to connect to the remote server' SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 41.180.70.243:80
I made sure that I can open the PDF in my browser when I use the link, and it works. (I get the link from an XML response from another server).
I am using service references to integrate to another system using SOAP. The result that I get back from the service is a XML file:
TPN_Test_ConsumerService.ConsumerSoapClient consumerServiceClient = new TPN_Test_ConsumerService.ConsumerSoapClient();
var result = consumerServiceClient.ConsumerEnquiry(securityInfo, moduleList, consumerBlock, enquiryBlock);
var PdfURL = "";
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(result));
XmlNodeList elemList = doc.GetElementsByTagName("PdfURL");
for (int i = 0; i < elemList.Count; i++)
{
PdfURL = elemList[i].InnerXml;
}
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
byte[] pdfBytes = client.DownloadData(PdfURL);
System.IO.File.WriteAllBytes("Path of file", pdfBytes);
I've tried setting the default proxy to false in the web.config file, but that also did not work.
Solution 1:[1]
You can download the PDF file and save it in Isolated Storage, to be able to view later offline. So lets see how to do it step-by-step.
1- Download PDF file from a link( URL ) provided by server side:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));
2- Save the downloaded PDF file in local storage:
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storageFile.OpenFile("your-file.pdf", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | e.ayoubi |
