Friday, April 22, 2016

Empty Recycle Bin programmatically using C#

Below is the sample code in C# to clean/empty the recycle bin of windows.

private static void EmptyRecycleBin()
{
string recycleLocation = String.Empty;
string strKeyPath = "SOFTWARE\\Microsoft\\Protected Storage System Provider";
 
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(strKeyPath);
string[] arrSubKeys = regKey.GetSubKeyNames();
if (IsVista() || IsWin7())   //Methods are described below
{
  recycleLocation = "$Recycle.bin";
}
else
{
  recycleLocation = "RECYCLER";
}

ObjectQuery query = new ObjectQuery("Select * from Win32_LogicalDisk Where DriveType = 3");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

ManagementObjectCollection queryCollection = searcher.Get();

foreach (ManagementObject mgtObject in queryCollection)
{
  string strTmpDrive = mgtObject["Name"].ToString();

  // default is true
  foreach (string strSubKey in arrSubKeys)
  {
    string regKeySID = strSubKey;
    string recycleBinLocation = (strTmpDrive + "\\" +
                recycleLocation + "\\" + regKeySID + "\\");

    if (recycleBinLocation != "" &&
     Directory.Exists(recycleBinLocation))
    {
      DirectoryInfo recycleBin = new
        DirectoryInfo(recycleBinLocation);

      // Clean Files
      FileInfo[] recycleBinFiles = recycleBin.GetFiles();
      foreach (FileInfo fileToClean in recycleBinFiles)
      {
        try {
            fileToClean.Delete();
        } catch (Exception)
        {
            // Ignore exceptions and try to move next file
        }
      }

   // Clean Folders
   DirectoryInfo[] recycleBinFolders=recycleBin.GetDirectories();
   foreach (DirectoryInfo folderToClean in recycleBinFolders)
   {
     try {
         folderToClean.Delete(true);
     } catch (Exception)
     {
         // Ignore exceptions and try to move next file
     }
    }
    Console.WriteLine("Cleaned up location:
     {0}",recycleBinLocation);
   }
  }
 }
}

private static bool IsVista()
{
   string majorOSVersion =
            Environment.OSVersion.Version.Major.ToString();

   if (majorOSVersion.Equals(Convert.ToString(6)))
       return true;
}

private static bool IsWin7()
{
   string majorOSVersion =
      Environment.OSVersion.Version.Major.ToString();

   if (majorOSVersion.Equals(Convert.ToString(7)))
      return true;
}

Share it if you like it.

No comments:

Post a Comment