【问题标题】:Dowload a pdf from a link with c#从带有 c# 的链接下载 pdf
【发布时间】:2016-07-28 01:21:22
【问题描述】:

我有一个windows服务应用程序,需要从不同的公共网站下载pdf文件并将它们本地保存到服务器上的一个文件夹中

我尝试使用 System.Net.WebClient 像这样执行下载

 client = new WebClient();
 client.DownloadFile(new Uri(fileLink, UriKind.Absolute), destination);

destination 是我需要将文件保存到的文件夹的完整路径和名称。例如:\server-name\downloads\file123.pdf

fileLink 是 pdf 文件的 url

我要保存的链接之一是:https://www.wvmmis.com/WV%20Medicaid%20Provider%20SanctionedExclusion/WV%20Medicaid%20Exclusions%20-%20June%202016.pdf

代码有效,但保存的文件已损坏,无法被 Acrobat 阅读器或任何 pdf 阅读器打开。

如果您单击上面的链接并执行另存为并将页面本地保存为 pdf,那么您可以正常打开它。所以问题不在于pdf真的损坏了,而是WebClient没有正确保存。

我可以对 WebClient 进行任何配置以使其正确保存文件,还是有另一种方法可以正确保存文件?

谢谢

【问题讨论】:

  • 看看这个:stackoverflow.com/questions/18712224/…希望对你有帮助
  • 在十六进制编辑器中打开文件。它是什么样的? Web 服务器可能不喜欢你的用户代理,而是给你一些 html 页面。

标签: c# pdf download webclient


【解决方案1】:

我很久以前写过类似的东西

try
{
    WebRequest request = WebRequest.Create(url);
    WebResponse response = request.GetResponse();
    string originalFileName = response.ResponseUri.AbsolutePath.Substring(response.ResponseUri.AbsolutePath.LastIndexOf("/") + 1);
    Stream streamWithFileBody = response.GetResponseStream();
    using (Stream output = File.OpenWrite(@"C:\MyPath\" + originalFileName))
    {
        streamWithFileBody.CopyTo(output);
    }

    Console.WriteLine("Downloded : " + originalFileName);
}
catch (Exception ex)
{
    Console.WriteLine("Unable to Download : " + ex.ToString());
}

【讨论】:

  • 我使用 WebRequest/WebResponse 尝试了您的代码,但仍然无法打开文件。仍然说它已损坏。
【解决方案2】:

在尝试了我在网上找到的所有示例之后,我终于找到了一种方法来做到这一点。我在这里发布我的答案,以防其他人遇到同样的问题。

我使用 selenium FireFoxDriver 导航到包含该链接的页面,然后找到该链接并单击它。我在firefox中创建了一个配置文件来直接下载文件类型pdf而不是打开它。

FirefoxDriver driver = new FirefoxDriver(myProfile);
driver.Navigate().GoToUrl(pageUrl);
driver.FindElement(By.LinkText(linkText)).Click();

您也可以通过 href 或 id 找到链接,但在我的情况下,我需要通过文本找到它。

【讨论】:

    猜你喜欢
    • 2014-09-09
    • 2015-07-24
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2019-02-16
    • 2019-03-23
    相关资源
    最近更新 更多