There is an old legend:
The files that are occupied can be forcibly deleted ...
If it is opened by another application, you must first find the open program and end it. or close the related process, delaying the method.
In general, being occupied means that there are other or thread-to-read or write operations on the file. If your program has a file stream read/write to the file, it is best to close the stream close () at the time of completion or exception, release the stream Dispose (), and do not prompt for the file to occupy, if it is not your own program causes the file to occupy, you need to restart the computer to delete, If you are still prompted to take up, you will have to end the process that occupies the file before you can delete it.
Solutions 1
To detect that a file is occupied by that process, you need to use the Microsoft-provided tool Handle.exe, which has Microsoft-provided downloads
We can call Handle.exe in C # to detect which process is consuming the file
stringFileName =@"C:\aaa.doc";//to check the files that were occupied by that processProcess Tool=NewProcess (); tool. Startinfo.filename="Handle.exe"; tool. Startinfo.arguments= filename+"/accepteula"; tool. Startinfo.useshellexecute=false; tool. Startinfo.redirectstandardoutput=true; tool. Start (); Tool. WaitForExit ();stringOutputtool =tool. Standardoutput.readtoend ();stringMatchpattern =@"(? <=\s+pid:\s+) \b (\d+) \b (? =\s+)";foreach(Match matchinchregex.matches (Outputtool, Matchpattern)) {Process.getprocessbyid (int. Parse (match. Value)). Kill ();}
Reference articles
WinForm, how to forcibly delete the occupied files
Jevan, using C # to detect a file is being consumed by that process
C # Forced deletion of files, some thoughts on the removal of occupation