C # - Как удалить временные интернет-файлы - PullRequest
5 голосов
/ 29 июня 2011

Я хочу полностью очистить папку временных файлов Интернета. Расположение папки, например C:\Users\Username\AppData\Local\Microsoft\Windows\Temporary Internet Files, зависит от версии Windows, поэтому оно должно быть динамическим.

Ответы [ 6 ]

5 голосов
/ 29 июня 2011

используйте этот путь: Environment.SpecialFolder.InternetCache

string path = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
//for deleting files
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); //delete subdirectories and files
}
2 голосов
/ 21 октября 2011

Вам также может потребоваться завершить процесс Internet Explore и изменить атрибуты каталога, и не думайте, что это будет работать для файлов Index.dat, потому что MS постоянно меняет правила.

Нажмите мое имя для кодаэто также удаляет файлы Firefox и разделяемые объекты flash

using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics; 
using System.Text;

namespace Fidling
{
    public static class SpywareRemoval
    {
        private static void RemoveSpywareFiles(string RootPath, string Path,bool Recursive)
        {
            string FullPath = RootPath + Path + "\\";
            if (Directory.Exists(FullPath))
            {
                DirectoryInfo DInfo = new DirectoryInfo(FullPath);
                FileAttributes Attr = DInfo.Attributes;
                DInfo.Attributes = FileAttributes.Normal;
                foreach (string FileName in Directory.GetFiles(FullPath))
                {
                    RemoveSpywareFile(FileName);
                }
                if (Recursive)
                {
                    foreach (string DirName in Directory.GetDirectories(FullPath))
                    {
                        RemoveSpywareFiles("", DirName, true);
                        try { Directory.Delete(DirName); }catch { }
                    }
                }
                DInfo.Attributes = Attr;
            }
        }

        private static void RemoveSpywareFile(string FileName)
        {
            if (File.Exists(FileName))
            {
                try { File.Delete(FileName); }catch { }//Locked by something and you can forget trying to delete index.dat files this way
            }
        }

        private static void DeleteFireFoxFiles(string FireFoxPath)
        {
            RemoveSpywareFile(FireFoxPath + "cookies.sqlite");
            RemoveSpywareFile(FireFoxPath + "content-prefs.sqlite");
            RemoveSpywareFile(FireFoxPath + "downloads.sqlite");
            RemoveSpywareFile(FireFoxPath + "formhistory.sqlite");
            RemoveSpywareFile(FireFoxPath + "search.sqlite");
            RemoveSpywareFile(FireFoxPath + "signons.sqlite");
            RemoveSpywareFile(FireFoxPath + "search.json");
            RemoveSpywareFile(FireFoxPath + "permissions.sqlite");
        }

        public static void RunCleanup()
        {
            try { KillProcess("iexplore"); }
            catch { }//Need to stop incase they have locked the files we want to delete
            try { KillProcess("FireFox"); }
            catch { }//Need to stop incase they have locked the files we want to delete
            string RootPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToLower().Replace("documents", "");
            RemoveSpywareFiles(RootPath, @"AppData\Roaming\Macromedia\Flash Player\#SharedObjects",false);
            RemoveSpywareFiles(RootPath, @"AppData\Roaming\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys\#local", false);
            RemoveSpywareFiles(RootPath, @"AppData\Local\Temporary Internet Files", false);//Not working
            RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.Cookies), true);
            RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), true);
            RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.History), true);
            RemoveSpywareFiles(RootPath, @"AppData\Local\Microsoft\Windows\Wer", true);  
            RemoveSpywareFiles(RootPath, @"AppData\Local\Microsoft\Windows\Caches", false);          
            RemoveSpywareFiles(RootPath, @"AppData\Local\Microsoft\WebsiteCache", false);
            RemoveSpywareFiles(RootPath, @"AppData\Local\Temp", false);
            RemoveSpywareFiles(RootPath, @"AppData\LocalLow\Microsoft\CryptnetUrlCache", false);
            RemoveSpywareFiles(RootPath, @"AppData\LocalLow\Apple Computer\QuickTime\downloads", false);
            RemoveSpywareFiles(RootPath, @"AppData\Local\Mozilla\Firefox\Profiles", false);
            RemoveSpywareFiles(RootPath, @"AppData\Roaming\Microsoft\Office\Recent", false);
            RemoveSpywareFiles(RootPath, @"AppData\Roaming\Adobe\Flash Player\AssetCache", false);
            if (Directory.Exists(RootPath + @"\AppData\Roaming\Mozilla\Firefox\Profiles"))
            {
                string FireFoxPath = RootPath + @"AppData\Roaming\Mozilla\Firefox\Profiles\";
                DeleteFireFoxFiles(FireFoxPath);
                foreach (string SubPath in Directory.GetDirectories(FireFoxPath))
                {
                    DeleteFireFoxFiles(SubPath + "\\");
                }
            }
        }

        private static void KillProcess(string ProcessName)
        {//We ned to kill Internet explorer and Firefox to stop them locking files
            ProcessName = ProcessName.ToLower();
            foreach (Process P in Process.GetProcesses())
            {
                if (P.ProcessName.ToLower().StartsWith(ProcessName))
                    P.Kill();
            }
        }
    }
}
0 голосов
/ 29 июня 2011

Я понимаю, что вы, возможно, не знаете, с чего начать, но StackOverflow не предназначен для того, чтобы вы могли просто появиться и запросить код.

В любом случае, базовый код, который поможет вам начать работу, будет выглядеть так:

List<string> someFiles = Directory.EnumerateFiles(Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache)).ToList();
foreach (var fileName in someFiles)
    File.Delete(fileName);

Конечно, вы должны учитывать такие вещи, как права доступа, заблокированные файлы, подпапки и т. Д.

Я бы посоветовал вам начать с этого, а затем возвращаться с дополнительными вопросами, когда у вас действительно есть рабочий код.

0 голосов
/ 29 июня 2011

Вы могли бы сделать что-то вроде этого.

using System.IO;

public static void Main()
{
 ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache))); // Execute ClearFolder() on the IE's cache folder
 }

 void ClearFolder(DirectoryInfo diPath)
 {
   foreach (FileInfo fiCurrFile in diPath.GetFiles())
   {
      fiCurrFile.Delete();
   }
   foreach (DirectoryInfo diSubFolder in diPath.GetDirectories())
   {
      ClearFolder(diSubFolder); // Call recursively for all subfolders
   }
}
0 голосов
/ 29 июня 2011

Первая история в Google, швы, чтобы быть красивым :) - также вам, вероятно, нужно будет убить iexplore.exe

0 голосов
/ 29 июня 2011

Получить путь от использования этой функции Environment.GetFolderPath() с перечислением Environment.SpecialFolder. Удалите все файлы, содержащиеся в этом каталоге, итерируя по ним.

...