WPF 中 Webview2 如何修改数据存储目录

2023年9月14日 974点热度 0人点赞 0条评论
内容纲要

默认 Webview2 会被安装到系统目录,可能会导致程序启动时权限不足,无法使用 Webview2,以及多版本程序之间发生存储目录冲突。
因此需要自定义设置 Webview2 目录,最好就存储在程序安装目录下。

首先修改 App.xaml 文件,添加一行:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ui:ThemesDictionary Theme="Light" />
                <ui:ControlsDictionary />
            </ResourceDictionary.MergedDictionaries>
            <!--修改 WebView2 -->
            <wv2:CoreWebView2CreationProperties x:Key="EvergreenWebView2CreationProperties" />
        </ResourceDictionary>
    </Application.Resources>

然后在程序启动时,修改目录位置。

            // 配置 webview2 数据存放位置
            var p = Application.Current.Resources["EvergreenWebView2CreationProperties"] as CoreWebView2CreationProperties;
            p!.UserDataFolder = GetWebView2UserDataFolder();
        // 配置 webview2 用户数据目录
        private static string GetWebView2UserDataFolder()
        {
            var applicationName = "当前程序的名称";
            var result = System.IO.Path.Combine("{程序安装目录}/localdata", $"{applicationName}.WebView2");

            return result;
        }

然后在使用 Webview2 的窗口,配置控件的属性。

                <Grid>
                    <wv2:WebView2 x:Name="webView" Source="http://localhost:666"
                              CreationProperties="{StaticResource EvergreenWebView2CreationProperties}" Margin="0,0,0,0" />
                </Grid>

如果使用的是 BlazorWebview ,那么可以绑定初始化事件,在初始化之前设定目录。

            InitializeComponent();
            this.webView.BlazorWebViewInitializing += (s, e) =>
            {
                e.UserDataFolder = "D:/xxxxxx";
            };

痴者工良

高级程序员劝退师

文章评论