【问题标题】:WebClient throw 'An exception occurred during WebClient request'WebClient throw 'WebClient 请求期间发生异常'
【发布时间】:2021-07-08 10:33:26
【问题描述】:

我知道这个问题在网上问了很多,但我没有找到满意的答案。

private string LocalSqlDriverDownloader()
{
    ProgBar prograssBar = new();
    string sqlLocalDBUrl = "https://download.microsoft.com/download/7/c/1/7c14e92e-bdcb-4f89-b7cf-93543e7112d1/SqlLocalDB.msi";
    string fileName = "SqlLocalDB.msi";
    string directory = $@"{Path.GetPathRoot(Environment.SystemDirectory)}Download"; // C:\Download
    if (!Directory.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }
    using WebClient webClient = new();
    webClient.DownloadProgressChanged += (s, e) =>
    {
        Application.Current.Dispatcher?.Invoke(() =>
        {
            (prograssBar.DataContext as PrograssbarWindowViewModel).PrograssBarValue = e.ProgressPercentage;
        });
    };
    webClient.DownloadFileCompleted += (s, e) =>
    {
        prograssBar.Close();
    };
    string downloadPath = $@"{directory}\{fileName}";
    try
    {
        webClient.DownloadFile(sqlLocalDBUrl, downloadPath);
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
    prograssBar.ShowDialog();
    return directory;
}

我不知道为什么这会向我抛出异常,我尝试下载其他文件,http 和 https,它与结果没有任何不同。

给定的异常:

System.Exception
  HResult=0x80131500
  Message=An exception occurred during WebClient request.
  Source=PulserTesterMultipleHeads
  StackTrace:
   at PulserTesterMultipleHeads.Models.MainTestPageMV.LocalSqlDriverDownloader() in C:\Project\Models\MainTestPageMV.cs:line 955
   at PulserTesterMultipleHeads.Models.MainTestPageMV.LocalSQLDriverInstaller() in C:\Project\Models\MainTestPageMV.cs:line 905
   at PulserTesterMultipleHeads.Models.MainTestPageMV..ctor(Action closeAction, String catalogDesc) in C:\Project\Models\MainTestPageMV.cs:line 70
   at PulserTesterMultipleHeads.UserControls.MainTestPage..ctor() in C:\Project\UserControls\MainTestPage.xaml.cs:line 31

【问题讨论】:

  • “我们不建议您在新开发中使用 WebClient 类。而是使用 System.Net.Http.HttpClient 类。” - WebClient Docs
  • 请在任何有关异常的问题中添加异常消息和堆栈跟踪。
  • @Fildor 异常消息和堆栈跟踪已添加,谢谢。
  • 你能突出显示第 955 行吗?
  • 内部有异常吗?

标签: c#


【解决方案1】:

移除整个结构:

try
{
    webClient.DownloadFile(sqlLocalDBUrl, downloadPath);
}
catch (Exception e)
{
    throw new Exception(e.Message);
}

替换为

webClient.DownloadFile(sqlLocalDBUrl, downloadPath);

那么你仍然会得到一个错误,但至少你将能够看到哪里出了问题。异常和内部异常会毫不含糊地告诉你哪里出了问题。堆栈跟踪会告诉你哪里出错了。

事实上,你已经添加了这个块,它所做的只是删除你需要找出问题所在的信息。我们无法告诉您具体出了什么问题,因为您的代码故意将其删除。

【讨论】:

  • 嗨,抱歉耽搁了,我没在工作。我收到以下两个错误: 1. ConfigurationErrorsException:为配置系统“system.net/defaultProxy”中指定的 Web 创建代理时出错。为此,我认为这是我的问题的答案 [stackoverflow.com/a/6268221/13295451] 2. SocketException:提供了一个无效的参数我从互联网上了解到的第一个是由于我的组织限制,但我无法理解什么无效我要发送的论点。
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多