How to download file into memory with WebView2?

50 views Asked by At

I want to download a file in WebView2 into memory instead of saving it to the disk. However, I can't find a method in WebView2 to allow me to do anything except change the path where the file will be stored on the disk, ie.

formWebView2.webView2.CoreWebView2.Profile.DefaultDownloadFolderPath = filePath;

This works to save it to the disk

TaskCompletionSource<bool> downloadTaskCompletionSource = new TaskCompletionSource<bool>();
formWebView2.webView2.CoreWebView2.DownloadStarting += delegate (object sender, CoreWebView2DownloadStartingEventArgs args) {
    args.DownloadOperation.StateChanged += delegate (object sender, Object e) {
    switch (args.DownloadOperation.State) {
        case CoreWebView2DownloadState.Completed:
            downloadTaskCompletionSource.TrySetResult(true); // Continue when the download is completed
            break;
        }
    };
};

// Click on the DOWNLOAD button
string script = @"(function(){
    var status = 'ERROR';
    const downloadDataButtons = document.getElementsByClassName('historical-data__controls-button--download historical-download');
    if (downloadDataButtons.length == 1) { // Check to make sure there is only one such button
        downloadDataButtons[0].click();
        status = 'OK';
    }
    return status;
})();";
string javaScriptResponse = await formWebView2.webView2.ExecuteScriptAsync(script);

await downloadTaskCompletionSource.Task; // Wait for the file to finish downloading

With WebClient, you could just use MemoryStream and StreamReader to save the file to memory and read it from memory

using (MemoryStream memoryStream = new MemoryStream(webClient.DownloadData(url))) {
    memoryStream.Position = 0; // Start the memoryStream at the beginning
    using (StreamReader streamReader = new StreamReader(memoryStream)) {
        for (int lineNumber = 0; lineNumber < memoryStream.Length; lineNumber++) {
            String line = streamReader.ReadLine();
        }
    }
}

Is there a way in WebView2 to download it to the MemoryStream instead of the disk? I could add a RAM disk, but among other drawbacks, I'd have to allocate a lot of extra RAM in case the user downloaded a large file.

0

There are 0 answers