-4

I'm new to programming in C#, and im looking for a quick solution. I have 2 buttons on form, one is calling the DownloadFileAsync(), and the second one should cancel this operation. Code of first button:

private void button1_Click(object sender, EventArgs e)
{
...
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}

Code of second button:

private void button2_Click(object sender, EventArgs e)
{
webClient.CancelAsync(); // yes, sure, WebClient is not known here.
}

Im looking for an idea how to solve this problem quickly (use the webClient from first function, in block of second).

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
Tomasz Szymański
  • 1,445
  • 13
  • 17

3 Answers3

4

That isn't a private variable. webClient goes out of scope. You will have to make it a member variable of the class.

class SomeClass {
    WebClient webClient = new WebClient();

    private void button1_Click(object sender, EventArgs e)
    {
        ...
        webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

You must to define webClient globally in your class (scope of variable). webClient on button2_Click is out of scope.

Form MSDN: Scopes

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs.

and

The scope of a member declared by a class-member-declaration is the class-body in which the declaration occurs.

so that

class YourClass 
{
     // a member declared by a class-member-declaration
     WebClient webClient = new WebClient();

    private void button1_Click(object sender, EventArgs e)
    {
        //a local variable 
        WebClient otherWebClient = new WebClient();
        webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        // here is out of otherWebClient scope
        // but scope of webClient not ended
        webClient.CancelAsync();
    }

}
Ria
  • 10,237
  • 3
  • 33
  • 60
0

The webclient is declared in button1_Click method and is avialble in the scope this method

Hence you cannot use it in button2_Click method

Instead the compiler will fail your build

To reslove this please move the webClient declaration outside the method and make it available at class level

HatSoft
  • 11,077
  • 3
  • 28
  • 43