Deleting "scratch" directories upon exiting
Dear Code Gurus,
I have an application that may create some scratch directories that should be deleted upone exiting. So, in my code for Form1 the following is done:
Code:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DeleteScratchDirectories();
}
I also want to make sure that those directories are deleted if some exceptions are triggered in Form1 while running, so the following is done in Program.cs:
Code:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 FPtr = null;
try
{
Application.Run(FPtr = new Form1());
}
catch (Exception e10)
{
// Clean up the created mess before exiting
if(FPtr!=null) FPtr.DeleteScratchDirectories();
MessageBox.Show(
String.Format("Application is exiting with errors:\n{0}", e10.ToString()),
"Exception Caught");
}
}
The code seems to compile and run with no problems.
Is this the correct way to handle situation like this? Are there any potential problems? Should anything be done in a different way?
Thank you for your help.
Re: Deleting "scratch" directories upon exiting
I have had to do this in some internal applications that I have written and I did it nearly the same way. You are handling the two cases that you need to handle (normal closing and a crash), and I don't know of any 'better' ways to do it.
Re: Deleting "scratch" directories upon exiting
If you only actually care about deleting scratch files, you can open all your scratch files with the "delete on close" flag which means no matter what happens your files will be deleted when your app exits, even if it's because someone nuked the process with task manager (or whatever).
Re: Deleting "scratch" directories upon exiting
Hey, I didn't even realize you could do that :). Shows what I know, nice one.