There are 3 forms. Each in turn opens, certain operations take place (downloading images, then converting them and pasting them into webbrowser fields). Upon completion of these operations, 2 and 3 forms are closed. 1 form remains open, i.e. the main one on which the initial download of these files takes place using WebClient.

And when I try to delete these files (forms 2 and 3 are already closed), I can’t do anything. They both were on a disk, and remain. Only after closing the program they disappear.

Downloading do this:

WebClient webClient = new WebClient(); webClient.DownloadFileAsync(new Uri(poster), disk.Text + System.IO.Path.GetFileName("poster" + pathExtString)); webClient.Dispose(); 

I insert images into webbrowser like this:

 Populate().ContinueWith((_) => {}, TaskScheduler.FromCurrentSynchronizationContext()); async Task PopulateInputFile_poster(HtmlElement file_poster) { file_poster.Focus(); // delay the execution of SendKey to let the Choose File dialog show up var sendKeyTask = Task.Delay(500).ContinueWith( (_) => { // this gets executed when the dialog is visible SendKeys.Send(disk + "" + "poster.jpg" + "{ENTER}"); }, TaskScheduler.FromCurrentSynchronizationContext() ); file_poster.InvokeMember("Click"); // this shows up the dialog await sendKeyTask; // delay continuation to let the Choose File dialog hide await Task.Delay(500); } foreach (HtmlElement file_poster in elements) { if (file_poster.GetAttribute("name") == "screen") { file_poster.Focus(); await PopulateInputFile_poster(file_poster); } } 

So, if you do not open this third form, where images are inserted into the webbrowser, then everything is fine and the files are deleted. But if you open it, nothing will come out even after the closure of the third form itself.

Delete the following:

 System.IO.File.Delete(disk.Text+"poster.jpg"); 

PS The second form does not always open, so there can be no exact questions about it.

    1 answer 1

    Perhaps WebBrowser saves the link to the file. In this case, you can try to go to another page and delete after the transition:

     void DeleteFile() { needToDeleteFile = true; //переходим на пустую страницу webBrowser.Navigate("about:blank"); } //обрабатываем событие перехода на страницу и затем удаляем файлы void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (needToDeleteFile) { File.Delete(fileName); needToDeleteFile = false; } } 

    I took the code from the answer to a similar question in English: How can I have the webbrowser control?

    Alternatively, you can try to explicitly free all WebBrowser resources:

     webBrowser.Dispose(); //попробовать удалить файлы после этого 
    • I tried to clear resources when closing the form. As a result, after closing the form and clicking on the button responsible for deleting files, nothing happened. But it was enough to close the program, as the file immediately disappeared ... - Andrei Fedorov