Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for system to delete file

Tags:

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...?

like image 896
Miro Avatar asked Feb 20 '12 23:02

Miro


People also ask

How do you force delete a system file?

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.

How do you force delete a file that won't 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.

Can't delete a file because it is open in system?

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.

How do you delete a file even if it is in use?

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.


1 Answers

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.

like image 132
Mike G Avatar answered Sep 20 '22 01:09

Mike G