Download a file through the WebBrowser control

Add a SaveFileDialog control to your form, then add the following code on your WebBrowser’s Navigating event:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    if (e.Url.Segments[e.Url.Segments.Length - 1].EndsWith(".pdf"))
    {
        e.Cancel = true;
        string filepath = null;

        saveFileDialog1.FileName = e.Url.Segments[e.Url.Segments.Length - 1];
        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            filepath = saveFileDialog1.FileName;
            WebClient client = new WebClient();
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadFileAsync(e.Url, filepath);
        }
    }
}

//Callback function

void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show("File downloaded");
}

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d338a2c8-96df-4cb0-b8be-c5fbdd7c9202

Leave a Comment