我想将WebView2中的文件下载到内存中,而不是保存到磁盘上。 但是,我在 WebView2 中找不到允许我执行任何操作的方法,除了更改文件在磁盘上存储的路径,即。
formWebView2.webView2.CoreWebView2.Profile.DefaultDownloadFolderPath = filePath;
这可以将其保存到磁盘
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
使用WebClient,您可以使用MemoryStream和StreamReader将文件保存到内存并从内存中读取它
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();
}
}
}
WebView2中有没有办法将其下载到MemoryStream而不是磁盘? 我可以添加 RAM 磁盘,但除其他缺点外,我必须分配大量额外的 RAM,以防用户下载大文件。
如果我正确理解你的问题,它与WebView2无关。
我使用这个(代码改编自 EssentialsObjects):
你需要你想要下载的文件的 url,然后你会得到一个字节数组;请自行决定使用它。
public static byte[] getDataFromUrl(string url)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.OpenRead(url);
int bytes_total = Convert.ToInt32(wc.ResponseHeaders["Content-Length"]);
System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
byte[] b = null;
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
try
{
response = (System.Net.HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
//error message here
return null;
}
if (request.HaveResponse)
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(receiveStream))
{
b = br.ReadBytes(bytes_total + 1000);
br.Close();
}
}
}
return b;
}