问题
How can I delete the file that has been navigated in the webbrowser? Error says "It is being used by another process"
preview_wb.Navigate(@"C:\mypdf.pdf");
private void close_btn_Click(object sender, EventArgs e)
{
preview_wb.Stop();
File.Delete(@"C:\mypdf.pdf");
}
回答1:
Usually people suggest this code:
webBrowser.Navigate("about:blank");
while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
File.Delete(fileName);
I don't like it. I prefer to handle DocumentCompleted event.
void DeleteFile()
{
needToDeleteFile = true;
webBrowser.Navigate("about:blank");
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (needToDeleteFile)
{
File.Delete(fileName);
needToDeleteFile = false;
}
}
回答2:
If you need the "preview" to persist after the file has been deleted, you probably don't have any choice but to copy the file and navigate to the copy instead.
If you're happy to clear the "preview" when the file is delete, just navigate away from it first:
private void close_btn_Click(object sender, EventArgs e)
{
preview_wb.Navigate("about:blank");
File.Delete(@"C:\mypdf.pdf");
}
That should do the trick.
回答3:
Have you tried finding the file via the internet explorer cache (using FindFirst/NextUrlCacheEntry API) and deleting it with DeleteUrlCacheEntry? There are pre-written examples on how to loop through and do the deletion on the new, just google it.
You will get 3 types of cache, on starting with "Cookie: ", another starting with "Visited: " - which just represents the visited sites list (it isn't the history, don't confuse the two), and the last type just comes in the form of a url begining with http:// or https://. Once you are looping through, you can pick and choose which ones you want to delete.
Let me know if you have any further questions, doing it this way should get rid of the "file in use" issue, if it doesn't, either .dispose or unload your webbrowser control before doing cache delete (but you probably won't need to).
来源:https://stackoverflow.com/questions/5495619/how-can-i-delete-the-file-that-has-been-navigated-in-a-webbrowser-control