Search code examples
c#private-membersdownloadfileasync

How do I access a variable declared in one function from a second function?


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).


Solution

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