C # Forced deletion of files, some thoughts on the removal of occupation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.