C# 在.NET2.0下工作的文件下载现在只在.NET4.6下工作
以下代码多年来仅使用.NET2.0运行良好。现在它停止了,只能与.NET4.6或更高版本一起使用。预算保持不变。调试器运行于 DownloadFileAsync(新Uri(sourceURL),目的地) 线路。但是不再下载任何东西了C# 在.NET2.0下工作的文件下载现在只在.NET4.6下工作,c#,asynchronous,download,C#,Asynchronous,Download,以下代码多年来仅使用.NET2.0运行良好。现在它停止了,只能与.NET4.6或更高版本一起使用。预算保持不变。调试器运行于 DownloadFileAsync(新Uri(sourceURL),目的地) 线路。但是不再下载任何东西了 using System; using System.ComponentModel; using System.Net; using System.Windows.Forms; namespace NewTest { public partial clas
using System;
using System.ComponentModel;
using System.Net;
using System.Windows.Forms;
namespace NewTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
StartDownload();
}
private void StartDownload()
{
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
string destination = "Tools.exe";
string sourceURL = "https://mysiteexample.com/download/Tools.exe";
client.DownloadFileAsync(new Uri(sourceURL), destination);
}
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Done");
}
}
}
多亏了亨克,我才能够获得更多关于我问题的信息。我的ISP开始需要TLS 1.2。因此,我必须添加以下代码。现在一切正常
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
因此,生成的代码是
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
string destination = "Tools.exe";
string sourceURL = "https://mysiteexample.com/download/Tools.exe";
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
client.DownloadFileAsync(new Uri(sourceURL), destination);
}
由于下载是在using块中启动的,而且是异步的,所以我非常确定WebClient在有时间发送请求或至少处理请求之前就被释放了。如果正在下载,则无法处理它still@Sami如果未包装在using语句中,也不起作用。是的,不要混合使用异步和同步代码,您应该等待所有异步方法。您需要将其存储在方法之外的某个位置。如果您在方法中有它,它也将在方法调用完成后被释放。在类中声明变量scope@Sami也试过了,同样的结果