我想使用 C# 中的 WinForms 从互联网(通过 https(下载文件
private void Button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
string user = "user";
string pwd = "pwd";
CredentialCache mycache = new CredentialCache();
if (!string.IsNullOrEmpty(url))
{
Thread thread = new Thread(() =>
{
//Uri uri = new Uri(url);
mycache.Add(new Uri(url), "Basic", new NetworkCredential(user, pwd));
client.Credentials = mycache;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition","attachment;filename="" + "a.zip" + """);
byte[] data = client.DownloadData(url);
response.BinaryWrite(data);
response.End();
});
thread.Start();
}
}
当我开始下载此行时: HttpResponse response = HttpContext.Current.Response;
抛出了一个异常
"HttpContext.Current.Response"抛出了一个类型为"System.NullReferenceException"的异常。
谁能帮我解决这个问题?
您正在考虑WebForms(经典 ASP.NET(。WinForms 不会有可用的 HttpContext,因为它假设您处于 Web 上下文中(您不是(。一些选项是 HttpClient
、 WebClient
或 HttpWebRequest
。
您的问题本身并不是 https://stackoverflow.com/a/14628308/120753 的重复,但它为您提供了做您需要的解决方案。