I had a problem with refreshing file list after deleting a file. When I gave command to delete file, the exception was thrown because the refresh method tried to access a file that was supposed to be deleted.
After some thought and debuging I came to conclusion that problem was in a fact that system needs some time to delete a file. And I solve it like this:
//Deleting file System.Threading.Thread.Sleep(2000); //Refreshing list
and it worked fine.
My question is
Is there a more elegant way to wait for system do delete file and then continue with code...?
To do this, start by opening the Start menu (Windows key), typing run , and hitting Enter. In the dialogue that appears, type cmd and hit Enter again. With the command prompt open, enter del /f filename , where filename is the name of the file or files (you can specify multiple files using commas) you want to delete.
One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.
This is the most promising method to fix the "file is open in another program" error. Click Ctrl + Shift + ESC to open the Task Manager. Alternatively, you can press Ctrl + Alt + Del or right-click the Taskbar and select Task Manager. If you're on Windows 11, the Taskbar right-click won't work.
4. In the command window, type the DEL /F file name command and press Enter to force delete the file that is in use. Note: In the above command, the file name must be replaced by the name of the file along with its extension that you want to delete. For example del /f TestFile.
This works for me:
public static void DeleteFile(String fileToDelete) { var fi = new System.IO.FileInfo(fileToDelete); if (fi.Exists) { fi.Delete(); fi.Refresh(); while (fi.Exists) { System.Threading.Thread.Sleep(100); fi.Refresh(); } } }
I find that most of the time, the while loop will not be entered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With