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

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

问题描述

我在表单上有一个WebBrowser控件,但大部分内容对用户来说都是隐藏的。它是处理一系列登录和其他任务。我必须使用此控件,因为有大量的Javascript可以处理登录。 (即,我不能切换到WebClient对象。)



在跳过一点之后,我们最终想要下载一个PDF文件。而不是下载,该文件显示在webBrowser控件中,用户看不到。



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

解决方案

将一个SaveFileDialog控件添加到表单中,然后在WebBrowser的导航事件中添加以下代码:

  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


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

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.

How can I download the PDF instead of having it load in the browser 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

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

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