How to delete recent ,prefetch and %temp% items in system using C#

Locked How to delete recent ,prefetch and %temp% items in system using C#

  • Tuesday, February 28, 2012 7:43 AM
     
     

    I want know How to delete recent ,prefetch and %temp%  items in system using C# code.

    Please explain with some code.

All Replies

  • Tuesday, February 28, 2012 8:40 AM
     
     Answered Has Code

    Hi Rajashekhar, I have written below function which deletes contents of temp, recent and prefetch folders (skipping the items which cannot be deleted). Just call the function CleanTemporaryFolders function.

    private void CleanTemporaryFolders()
    {
        String tempFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
        String recent = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + "\\Recent";
        String prefetch = Environment.ExpandEnvironmentVariables("%SYSTEMROOT%") + "\\Prefetch";
        EmptyFolderContents(tempFolder);
        EmptyFolderContents(recent);
        EmptyFolderContents(prefetch);
    }
            
    private void EmptyFolderContents(string folderName)
    {
        foreach (var folder in Directory.GetDirectories(folderName))
        {
            try
            {
                Directory.Delete(folder, true);
            }
            catch (Exception excep)
            {
                System.Diagnostics.Debug.WriteLine(excep);
            }
        }
        foreach (var file in Directory.GetFiles(folderName))
        {
            try
            {
                File.Delete(file);
            }
            catch (Exception excep)
            {
                System.Diagnostics.Debug.WriteLine(excep);
            }
        }
    }

    I hope this helps.

    Please mark this post as answer if it solved your problem. Happy Programming!

    • Marked As Answer by Rajashekar Goud Tuesday, February 28, 2012 11:29 AM
    •  
  • Tuesday, February 28, 2012 11:30 AM
     
     
    Thanks Adavesh.
  • Tuesday, February 28, 2012 12:39 PM
     
     
    we need to add any Namespaces
  • Wednesday, February 29, 2012 6:14 AM
     
     Answered
    You only need System & System.IO namespaces.

    Please mark this post as answer if it solved your problem. Happy Programming!

  • Thursday, March 08, 2012 7:14 AM
     
     
    Can u Pls let me how to delete  js,img,txt files and etc from Temporary Internet Files.