通过 WebBrowser 控件下载文件 [英] Download a file through the WebBrowser control

查看:34
本文介绍了通过 WebBrowser 控件下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单上有一个 WebBrowser 控件,但在大多数情况下,它对用户是隐藏的.它用于处理一系列登录和其他任务.我必须使用这个控件,因为有大量的 Javascript 来处理登录.(即,我不能只切换到 WebClient 对象.)

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 this control because there is a ton of Javascript that handles the login. (i.e., I can't just switch to a WebClient object.)

在徘徊了一会儿之后,我们最终想要下载一个 PDF 文件.但是文件不是下载,而是显示在 webBrowser 控件中,用户看不到.

After hopping around a bit, we end up wanting to download a PDF file. But instead of downloading, the file is displayed within the webBrowser control, which the user can not see.

如何下​​载 PDF 而不是在浏览器控件中加载它?

How can I download the PDF instead of having it load in the browser control?

推荐答案

向表单添加 SaveFileDialog 控件,然后在 WebBrowser 的 Navigating 事件中添加以下代码:

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

//回调函数

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

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

这篇关于通过 WebBrowser 控件下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆