通过webview2下载文件时候会将文件保存在用户的默认下载目录,
如果想调整成通过弹窗选择下载路径的方式则需要将默认行为做出修改。
本文通过CoreWebView2_DownloadStarting 这个事件来调整下载路径,
基本思路为通过弹窗让用户选择需要保存的路径,如果用户取消了此操作则通过这个事件提供的Handled句柄取消下载行为。
如果输入下载文件的路径、文件名后则只是修改此事件的目标文件名,而不影响其他逻辑。
相关代码如下
private void CoreWebView2_DownloadStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2DownloadStartingEventArgs e)
{
//string fileName = e.ResultFilePath;
//string downloadUrl = e.DownloadOperation.Uri;
// 弹出保存文件对话框,让用户选择保存路径和文件名
var saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.Filter = "*.*|*.*";
saveFileDialog.FileName = e.ResultFilePath;
if (saveFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
//取消默认下载的行为
e.Handled = true;
return;
}
//重置下载路径后使用原webview行为继续下载
e.ResultFilePath = saveFileDialog.FileName;
return;
}
private void webView2_Loaded(object sender, RoutedEventArgs e)
{
webView2.ContentLoading += WebView2_ContentLoading;
}
private void WebView2_ContentLoading(object sender, Microsoft.Web.WebView2.Core.CoreWebView2ContentLoadingEventArgs e)
{
webView2.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
}