0

I want to download a file from the internet (over https) using WinForms in C#

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();
    }
}

When I start to download this line: HttpResponse response = HttpContext.Current.Response; threw an exception

'HttpContext.Current.Response' threw an exception of type 'System.NullReferenceException'`.

Can anyone help me solve this problem?

PaulG
  • 13,871
  • 9
  • 56
  • 78
John.D
  • 55
  • 1
  • 7
  • The example you've taken this code from is probably ASP.NET code. There is no `HttpContext.Current` in Winforms. A winforms example is similar to : https://stackoverflow.com/questions/52764470 – PaulG May 29 '19 at 17:01

1 Answers1

0

You're thinking of WebForms (classic ASP.NET). WinForms would not have an HttpContext available as it assumes you are in a web context (which you are not). Some options are HttpClient, WebClient, or HttpWebRequest.

You question in and of itself isn't a duplicate of https://stackoverflow.com/a/14628308/120753 but it provides you a solution to do what you need.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
  • Also note that, at least in .net framework, accessing the http context from another thread usually ends up being null itself. – Silvermind May 29 '19 at 17:04
  • True, but that is secondary to the fact that this is a desktop application and not processing an HTTP request. – Babak Naffas May 29 '19 at 17:06