Download a file through the WebBrowser control

前端 未结 3 464
南旧
南旧 2020-12-01 15:26

I have a WebBrowser control on a form, but for the most part it remains hidden from the user. It is there to handle a series of login and other tasks. I have to use<

3条回答
  •  星月不相逢
    2020-12-01 15:45

    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

提交回复
热议问题