-1

I am creating a C# application. This app is deleting temporary folders. But some processes are being used. That's why it can't remove them. And i have to skip those files. I hope you can help.

Code:

// Clearing folder's content (\)
void ClearFolder(string FolderName)
{
    try
    {
        if (Directory.Exists(FolderName))
        {
            DirectoryInfo dir = new DirectoryInfo(FolderName);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.IsReadOnly = false;
                fi.Delete();
                CleanLog.Items.Add(fi.FullName + " " + "is found and deleted");
            }

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                ClearFolder(di.FullName);
                di.Delete();
                CleanLog.Items.Add(di.FullName + " " + "is found and deleted");
            }
        }
        else
        {
            CleanLog.Items.Add(FolderName + " " + "is not found.");
        }
    }
    catch (Exception Error)
    {
        MessageBox.Show(Error.Message, "Error", MessageBoxButtons.OK);
    }
}
// Clearing folder's content (\)

private void Clean_MouseDown(object sender, MouseEventArgs e)
{
    // Folder Locations
    string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Temp"; // Temp
    string Temp2 = Path.GetTempPath(); // %Temp%
    // Folder Locations

    // Clearing folders
    ClearFolder(Temp);
    ClearFolder(Temp2);
    // Clearing folders
}
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
Gorkido
  • 11
  • 1

1 Answers1

0

To achieve this, you can also use try catch for the delete statement like

try
{
  fi.Delete();
}
catch
{
  //Your message...
}
Ashish Sinha
  • 87
  • 2
  • 10
  • @silkfire Have you read https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.delete?view=net-5.0#exceptions ? – Caius Jard Aug 10 '21 at 15:43