2

I am unable to delete the temporary folders directory. This is my code:

private void button8_Click(object sender, EventArgs e)
{
    if(checkBox5.Checked == true)
    {
        try
        {
            string fileDirectory = @"C:\Users\Admin\AppData\Local\Temp";
            if(Directory.Exists(fileDirectory))
            {
                Directory.Delete(fileDirectory);
            }
        }
        catch(IOException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    else
    {
        MessageBox.Show("System has been cleaned!");
    } 
}
Steve
  • 2,950
  • 3
  • 21
  • 32
  • Tell us what the error message is. A wild guess is that you don't have permission to delete that directory. – Rotem Oct 07 '15 at 08:37
  • 8
    Temporary files are created by many Windows applications and by Windows itself. First of all many files will be in use then you can't delete that directory and secondly...you shouldn't delete that folder!!! – Adriano Repetti Oct 07 '15 at 08:39
  • Ok so when I run the program and click the "Clean" button it says directory is not empty. –  Oct 07 '15 at 09:07
  • Modify the directory.delete(filedirectory) to directory.delete(filedirectory,true) – R Quijano Oct 07 '15 at 09:16
  • Delete the contents of that folder not the folder. You can't recreate that folder easily, it might have special permissions. – usr Oct 07 '15 at 09:25
  • The code didn't work but thanks for the help also I have no idea what that code is doing it looks pretty complex the first part. I had another error, some files are in use like my dropbox files are in use, and that pops up part of the error. –  Oct 07 '15 at 11:57

1 Answers1

3

You can use Path.GetTempPath() to get the current user's temporary folder. You shouldn't delete the Temp directory itself. It's better to delete it's files, skipping all the files you couldn't delete:

System.IO.DirectoryInfo tempDir = new DirectoryInfo(Path.GetTempPath());

foreach (FileInfo file in tempDir.GetFiles())
{
    try
    {
        file.Delete(); 
    }
    catch(IOException ex)
    {
        .....
    }
}

See also: "Directory is not empty" error when trying to programmatically delete a folder

Community
  • 1
  • 1
enkryptor
  • 1,574
  • 1
  • 17
  • 27