删除除C#中的文件以外的所有文件夹

删除除C#中的文件以外的所有文件夹

问题描述:

删除除文件(index.dat)之外的目录中的所有内容我试图清除Cookie文件夹和文件的临时文件夹,但出现错误当我尝试删除index.dat,因为它被另一个进程使用。有没有办法删除temp和cookies文件夹中的所有内容,但 index.dat文件除外?这里是我的代码:删除除C#中的文件以外的所有文件夹

string userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); 
string strDirLocalq = Path.Combine(userProfile, "AppData"); 
string strDirLocalw = Path.Combine(strDirLocalq, "Roaming"); 
string strDirLocale = Path.Combine(strDirLocalw, "Microsoft"); 
string strDirLocalr = Path.Combine(strDirLocale, "Windows"); 
string strDirLocalt = Path.Combine(strDirLocalr, "Cookies"); 

string[] filePaths = Directory.GetFiles(strDirLocalt); 
foreach (string filePath in filePaths) 
    File.Delete(filePath); 
+3

您可以将您的'File.Delete()'放在try/catch块中,以处理无法删除的文件,而不会中断循环(如果您这样选择的话)。 – Jon 2011-04-01 23:26:03

这工作:

string[] filePaths = Directory.GetFiles(strDirLocalt); 
foreach (string filePath in filePaths) 
{ 
    var name = new FileInfo(filePath).Name; 
    name = name.ToLower(); 
    if (name != "index.dat") 
    { 
     File.Delete(filePath); 
    } 
} 
+0

谢谢,它的工作。 – llk 2011-04-01 23:34:53

+0

不客气:-)我稍微修改它以使用FileInfo类。 – Pol 2011-04-01 23:39:42

刚刚从名单中筛选,它

foreach (string filePath in filePaths.Where(!filePath.Contains("index.dat")) 
    File.Delete(filePath); 
+1

如果您要更一般地应用它,修改要跳过的文件列表会很麻烦。如果您要使用where-not样式,将来可以节省您将所有跳过的文件放入静态数组,然后使用'filePaths.Where(fp =>!skipped.Any(s => fp.Contains (s)))'...... – Jon 2011-04-01 23:28:53

只需将围绕File.Delete一个try/catch,因为可能有更多的文件正在使用中也将抛出例外。

try 
{ 
    File.Delete(filePath); 
} 
catch (Exception ignore) 
{ 
} 
+1

这很好。无论如何,你仍然需要遍历文件,所以我会结合2解决方案:tster's和Hams的 – Adi 2011-04-01 23:29:12

为什么不只是捕捉到了异常 - 也就是任何文件可能是在使用的时候你试图删除它们possiblility。

try{ 
    // delete 
} 
catch{ 
} 

string[] filePaths = Directory.GetFiles(strDirLocalt); 
foreach (string filePath in filePaths) 
try { 
    File.Delete(filePath); 
} 
catch{ } 
} 

看看这个有趣的解决方案!

List<string> files = new List<string>(System.IO.Directory.GetFiles(strDirLocalt)); 
files.ForEach(x => { try { System.IO.File.Delete(x); } catch { } }); 

感受语言之美!

+0

这也工作。谢谢!它抓取当前“正在使用”的任何文件,并阻止它被删除。 – llk 2011-04-01 23:51:23

+0

Lambdas使这个郎愉快使用:) – Nickon 2013-05-13 12:46:16

一种方法可能仍然工作,是在安全模式下启动和然后指派自己的管理员权限,然后看看你能不能找到要删除的文件他们

我现在用的方法是创建一个批处理文件来重命名包含index.bat文件的文件夹下的子文件夹,然后仅将这些文件夹复制回原始位置,该位置不包含这些文件,但生成的批处理文件需要从单独的满足条件的Windows帐户运行管理员权限。