通过WebBrowser控件下载文件 [英] Download a file through the WebBrowser control
问题描述
在跳过一点之后,我们最终想要下载一个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);
}
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");
}
这篇关于通过WebBrowser控件下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!