Downloading a file async

I suppose that’s one way you might do it, but here is another:

private void button1_Click(object sender, System.EventArgs e)
{
    WebRequest request = WebRequest.Create("http://www.mcfunley.com/stuff/hi.txt");
    AsyncCallback callback = new AsyncCallback(this.GotFile);
    IAsyncResult res = request.BeginGetResponse(callback, request);
}

private void GotFile(IAsyncResult r)
{
    if(this.InvokeRequired)
    {
        this.Invoke(new AsyncCallback(this.GotFile), new object[]{r});
        return;
    }
    WebRequest request = (WebRequest)r.AsyncState;
    WebResponse response = request.EndGetResponse(r);
    using(StreamReader reader = new StreamReader(response.GetResponseStream(), true))
    {
        this.richTextBox1.Text = reader.ReadToEnd();
    }
}

Tags: , ,

Leave a Reply