How to Modify Data Storage Directory in WebView2 for WPF

2023年9月14日 50点热度 0人点赞 0条评论
内容目录

Default WebView2 will be installed in the system directory, which may lead to insufficient permissions when the program starts, preventing the use of WebView2, and can also cause storage directory conflicts between multiple versions of the program.

Therefore, it is necessary to customize the WebView2 directory settings, preferably storing it in the program's installation directory.

First, modify the App.xaml file and add a line:

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

Then, during the program startup, modify the directory location.

            // Configure WebView2 data storage location
            var p = Application.Current.Resources["EvergreenWebView2CreationProperties"] as CoreWebView2CreationProperties;
            p!.UserDataFolder = GetWebView2UserDataFolder();
        // Configure WebView2 user data directory
        private static string GetWebView2UserDataFolder()
        {
            var applicationName = "Current Program Name";
            var result = System.IO.Path.Combine("{Program Installation Directory}/localdata", $"{applicationName}.WebView2");

            return result;
        }

Then, in the window using WebView2, configure the properties of the control.

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

If you are using BlazorWebView, you can bind to the initialization event and set the directory before initialization.

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

痴者工良

高级程序员劝退师

文章评论