簡體   English   中英

如何使用 URL 鏈接下載 PDF 文件到 c# 中的本地計算機

[英]How do I download a PDF file using a URL link to local computer in c#

我正在嘗試使用 URL 鏈接將 pdf 文件下載到我的計算機,但它給出了以下錯誤:

'Unable to connect to the remote server' SocketException: 連接嘗試失敗,因為連接方在一段時間后沒有正確響應,或建立連接失敗,因為連接的主機沒有響應 41.180.70.243:80

當我使用該鏈接時,我確保可以在瀏覽器中打開 PDF,並且它可以工作。 (我從另一台服務器的 XML 響應中獲取鏈接)。

我正在使用服務引用來集成到另一個使用 SOAP 的系統。 我從服務返回的結果是 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);

我嘗試在 web.config 文件中將默認代理設置為 false,但這也不起作用。

您可以下載 PDF 文件並將其保存在獨立存儲中,以便以后離線查看。 因此,讓我們一步一步地看看如何做到這一點。

1-從服務器端提供的鏈接(URL)下載PDF文件:

WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));

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