-2

Hi i am actually creating a program to delete all the temp files and folders when an event is triggered. so for that i am using the following code but its not working and throwing an exception

enter image description here

And also for this i am using the code

   private void tempfiles_Click(object sender, EventArgs e)
    {
        if(tempcheck.Checked)
        {
            string tempPath = System.IO.Path.GetTempPath();
            System.IO.DirectoryInfo di = new DirectoryInfo(tempPath);
            try
            {
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
            }
            catch(Exception env)
            {
                MessageBox.Show("Please close all the applications and try \n" + env);
            }
        }
        else
        {
            MessageBox.Show("Please check the checkbox");
        }
    }

Here i want to delete the folders and files without any exception but in java i use method like fileonclose().

Raj
  • 101
  • 1
  • 2
  • 10

1 Answers1

1

If files are being used by another program, you will not be able to delete them. You should put your try...catch statement inside each for loop. That way you can continue trying to delete files even if one attempt fails.

To make your program more useful, you can keep track of which files were not deleted and create a log or open a window to show the file names to the user.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268