1

I have create a program that delete a folder. Like this :

    if (Directory.Exists((System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "My Dir Name"))))
    {
        Directory.Delete(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "My Dir Name"), true);
    }

this is alright . But a file that name is "Delete.exe" is in directory of "My Dir Name" [Like my code ] ! It gave an error, because "Delete.exe" is running and can't delete .

What can I do to delete, "Delete.exe"?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • possible duplicate of [How do I delete a file which is locked by another process in C#?](http://stackoverflow.com/questions/1040/how-do-i-delete-a-file-which-is-locked-by-another-process-in-c) – It'sNotALie. Jun 30 '13 at 22:27
  • This is a duplicate question of http://stackoverflow.com/questions/2245201/how-can-i-make-my-net-application-erase-itself, http://stackoverflow.com/questions/1305428/self-deletable-application-in-c-sharp-in-one-executable, and http://stackoverflow.com/questions/5303783/how-to-make-a-running-excutable-delete-its-own-file, or possibly even http://stackoverflow.com/questions/1040/how-do-i-delete-a-file-which-is-locked-by-another-process-in-c – caesay Jun 30 '13 at 22:32

1 Answers1

1

You're trying to delete the folder in which your running application is in and therefore delete the program itself? Well, you have a few options. It is interesting to note as well that batch files can delete themselves. So, that also leaves you a few more options:

  1. have your C# program copy itself to a temp directory before deleting the folder, and run from there.
  2. use a batch file entirely instead of C# - having it do whatever and then delete itself afterwards.
  3. have your C# program generate and execute a batch file and then quit - leaving the batch file to clean up after the C# program exits.
  4. run a CLI command to delete your program after a specified time:
    • Process.Start("cmd.exe", "/C ping 1.1.1.1 -n 1 -w 3000 > Nul & Del " + Application.ExecutablePath);
  5. you can use MovFileEx to specify to have your program deleted on next start up.

Most of these answers imply that the running EXE is your own appliation. if it is not, though - #5 will still work. you can schedule it to be deleted the next time the computer starts.

caesay
  • 16,932
  • 15
  • 95
  • 160