How to Change/Set the download default location of webview in c#

Viewed 1100

I have designed windows form application, in which i have implemented Webview. In that i am navigating to different Url using webview.Navigate. After navigating , i am downloading file from that url. And file is downloading successfully, but it is downloading in default location i.e. C:\Users\XYZ\Downloads.

I want to change the default download location of webview. Can we change the default download location of webview. Or is there any other way to download at different location from webview.

Thanks for the help

1 Answers

assuming you are using below or higher version of nuget WebView2 package for your application:

Install-Package Microsoft.Web.WebView2 -Version 1.0.865-prerelease

in order to manage download progress you may try code below:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load += Form1_Load;
    }
    private async void Form1_Load(object sender, EventArgs e)
    {
        BirWV.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
        await InitializeAsync(BirWV);
        BirWV.CoreWebView2.Navigate("https//myurl.com");
    }
    private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
    {
        downloadOperation = e.DownloadOperation; 
        e.ResultFilePath = @"C:\mytargetdowloadpath\mydownloadedfile.zip";
    }
    public async Task InitializeAsync(WebView2 wv, string webCacheDir = "")
    {
        CoreWebView2EnvironmentOptions options = null;
        string tempWebCacheDir = string.Empty;
        CoreWebView2Environment webView2Environment = null;
        tempWebCacheDir = webCacheDir;
        if (String.IsNullOrEmpty(tempWebCacheDir))
        {
            tempWebCacheDir = System.IO.Path.GetTempPath();
            tempWebCacheDir = System.IO.Path.Combine(tempWebCacheDir, System.Guid.NewGuid().ToString("N"));
        }
        webView2Environment = await CoreWebView2Environment.CreateAsync(null, tempWebCacheDir, options);
        await wv.EnsureCoreWebView2Async(webView2Environment);
        var initTaskField = BirWV.GetType().GetField("_initTask", BindingFlags.Instance | BindingFlags.NonPublic);
        dynamic initTask = initTaskField.GetValue(wv);
        BirWV.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
    }
    private void WebView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
    {
    }
}

Please check WebView_CoreWebView2InitializationCompleted method is being reached after running in debug mode.

Related