如何使用.NET清除IE的缓存(Temporary Internet Files)

如果你想写一段清除IE缓存的.NET代码,搜索互联网,你应该能发现一段这样的代码:

void EmptyCacheFolder(DirectoryInfo folder)
        {
            foreach (FileInfo file in folder.GetFiles())
            {
                file.Delete();
            }
 
            foreach (DirectoryInfo subfolder in folder.GetDirectories())
            {
                EmptyCacheFolder(subfolder);
            }
        }
 
 
        //Function which is used for clearing the cache
        bool ClearCache()
        {
            bool Empty;
            try
            {
                EmptyCacheFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)));
                Empty = true;
            }
 
            catch
            {
                Empty = false;
            }
 
            return Empty;
 
        }

 

但当你实际运行这段代码是,却发现无论如何也没有办法让这段代码稳定的运行,并且IE缓存目录下的文件似乎也无法删除,这是为什么呢?

应为在这段代码中,当你试图去删除Temporary Internet Files目录下的文件时,某一些文件因为是系统文件,或者是正在被浏览器使用,就会抛出IO的exception,整个foreach循环就会终止。

首先,我们应该把代码放到try中,保证不会因为exception导致循环的终止,其次,对于有IO冲突无法删除的文件,应该注册为下次启动是自动删除,这样就可以保证彻底的上除IE缓存文件。

具体的代码可以参考:

Your Internet Explorer's Secrets

posted on 2009-08-10 17:50  m2land  阅读(2973)  评论(0编辑  收藏  举报

导航