You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI3中WebView2是否支持自定义下载目录?求解决方法

WebView2 指定自定义下载目录的解决方案

WebView2 完全支持自定义下载路径,核心是通过监听 CoreWebView2.DownloadStarting 事件拦截下载请求,修改保存路径。具体实现步骤如下:

  • 确保WebView2控件完成初始化:必须等待 CoreWebView2 实例创建完成后,才能订阅下载事件。通常在控件初始化完成事件或调用 EnsureCoreWebView2Async() 后处理。
  • 订阅 DownloadStarting 事件:在事件回调中自定义下载目录和文件路径,覆盖默认保存位置。

示例代码(C# WinForms)

private async void Form_Load(object sender, EventArgs e)
{
    // 初始化CoreWebView2
    await webView21.EnsureCoreWebView2Async();
    // 订阅下载开始事件
    webView21.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
}

private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
{
    // 按自定义规则生成下载目录(示例:桌面下按日期创建文件夹)
    string customDownloadDir = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        $"WebView2_Downloads_{DateTime.Now:yyyyMMdd}"
    );

    // 目录不存在则创建
    if (!Directory.Exists(customDownloadDir))
    {
        Directory.CreateDirectory(customDownloadDir);
    }

    // 拼接最终文件保存路径
    string targetFilePath = Path.Combine(customDownloadDir, e.ResultFileName);
    // 指定下载路径
    e.DownloadOperation.ResultFilePath = targetFilePath;

    // 可选:设置为true可取消默认的下载弹窗,直接按指定路径保存
    e.Handled = true;
}

扩展说明

  • 可根据下载属性调整目录规则:比如通过 e.Uri 获取下载来源URL、e.MimeType 获取文件类型,以此生成分类文件夹。
  • 权限注意:确保程序拥有目标目录的创建和写入权限,避免因权限不足导致下载失败。
  • WPF环境逻辑一致:仅控件初始化方式略有差异,DownloadStarting 事件处理逻辑完全相同。

内容的提问来源于stack exchange,提问作者史新雨

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:25:27