如果你想寫一段清除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