0

Hey guys so I'm working on a small program which sorta speeds up your pc, but I have a problem I get an exception if I try to delete files, I believe cause they are in use. Though it deletes some, but not much. My question is how to delete files in use, and how to delete sub folders inside the folder

//this is my directory:

DirectoryInfo tempPath = new DirectoryInfo(@"C:\Users\" + Environment.UserName + @"\AppData\Local\Temp");

private void button8_Click(object sender, EventArgs e)
{           
    if (checkBox5.Checked)
    {
        //loop through these files
        foreach (FileInfo file in tempPath.GetFiles())
        {
            //delete files in content
            file.Delete();
        }
    }
}
Rob
  • 26,989
  • 16
  • 82
  • 98
  • aye, the old 'speed up your PC by deleting everything' trick... There is a post on checking if a file is locked here: http://stackoverflow.com/questions/1304/how-to-check-for-file-lock. Deleting a locked file is a complete different animal, however. – AJ X. Feb 04 '16 at 04:26
  • Possible duplicate of [How to delete all files and folders in a directory?](http://stackoverflow.com/questions/1288718/how-to-delete-all-files-and-folders-in-a-directory) – Gyuri Majercsik Feb 04 '16 at 04:26
  • MoveFileEx delay until reboot –  Feb 04 '16 at 04:27

1 Answers1

0

You must delete Folder recursivly with set FileAttributes normal.

private static void DeleteAllFolderRecursive(DirectoryInfo yourBaseDir)  
{  
    baseDir.Attributes = FileAttributes.Normal;  
    foreach (var childDir in baseDir.GetDirectories())  
        DeleteFolderRecursive(childDir);  

    foreach (var file in baseDir.GetFiles())  
        file.IsReadOnly = false;  

    baseDir.Delete(true);  
}  

And you call this :

DirectoryInfo tempPath = new DirectoryInfo(@"C:\Users\" + Environment.UserName + @"\AppData\Local\Temp");
DeleteAllFolderRecursive(tempPath);
4b0
  • 21,981
  • 30
  • 95
  • 142
  • Thanks for help. Shree this one is confusing what is basedir? Doesn't even exist. –  Feb 04 '16 at 05:10
  • Edit I had a question for programming why in the method we made add parameter when we can just type it below the method? Because we aren't going to use that parameter anyways when we call the method. We are usinf the tempPath one. –  Feb 04 '16 at 05:18
  • Also added this and I get error catch(IOException) { Directory.Delete(tempPath); } catch (UnauthorizedAccessException) { Directory.Delete(tempPath); } //though the error is Error CS1503 Argument 1: cannot convert from 'System.IO.DirectoryInfo' to 'string' –  Feb 04 '16 at 05:58