简体   繁体   English

如何使用 URL 链接下载 PDF 文件到 c# 中的本地计算机

[英]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:我正在尝试使用 URL 链接将 pdf 文件下载到我的计算机,但它给出了以下错误:

'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 'Unable to connect to the remote server' SocketException: 连接尝试失败,因为连接方在一段时间后没有正确响应,或建立连接失败,因为连接的主机没有响应 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.当我使用该链接时,我确保可以在浏览器中打开 PDF,并且它可以工作。 (I get the link from an XML response from another server). (我从另一台服务器的 XML 响应中获取链接)。

I am using service references to integrate to another system using SOAP.我正在使用服务引用来集成到另一个使用 SOAP 的系统。 The result that I get back from the service is a XML file:我从服务返回的结果是 XML 文件:

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.我尝试在 web.config 文件中将默认代理设置为 false,但这也不起作用。

You can download the PDF file and save it in Isolated Storage, to be able to view later offline.您可以下载 PDF 文件并将其保存在独立存储中,以便以后离线查看。 So lets see how to do it step-by-step.因此,让我们一步一步地看看如何做到这一点。

1- Download PDF file from a link( URL ) provided by server side: 1-从服务器端提供的链接(URL)下载PDF文件:

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: 2- 将下载的 PDF 文件保存在本地存储中:

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM