我想使用C#中的WinForms从Internet(通过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”的异常。
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
您正在考虑WebForms(经典ASP.NET)。 WinForms将没有HttpContext可用,因为它假定您处于Web上下文中(不是)。某些选项是HttpClient
,WebClient
或HttpWebRequest
。
您所提出的问题本身并不是https://stackoverflow.com/a/14628308/120753的重复,但它为您提供了解决所需的解决方案。