Reputation: 121
I am creating browser cleaner software and i am trying clear the all the cache files in the directory
C:\Users\RamRo\AppData\Local\Google\Chrome\User Data\Default\Cache
I am using this code to delete the files but trying to delete this
private void button3_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Users\RamRo\AppData\Local\Google\Chrome\User Data\Default\Cache");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
But when i try to execute this program struggling with this issue
Upvotes: 1
Views: 287
Reputation: 29022
With respect to both previous answers, your code should probably look something like this:
private void button3_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Users\RamRo\AppData\Local\Google\Chrome\User Data\Default\Cache");
List<FileSystemInfo> notDeletable = new List<FileSystemInfo>();
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch (Exception ex)
{
notDeletable.Add(file);
}
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
try
{
dir.Delete(true);
}
catch (Exception ex)
{
notDeletable.Add(dir);
}
}
// Process 'notDeletable' List
}
Maybe you should even make the Directory part recursive...
Upvotes: 1
Reputation: 67195
Well, almost certainly the answer is that the file is in use. The cache is used after all! With respect to deleting folders, that will fail if the folders contains any files or subfolders.
Any code that performs this task will have to deal with potential errors, and should graciously handle any errors trying to delete such files. You should read about try...catch
.
Upvotes: 2