Delete everything in a directory except a file in C#
11,981
Solution 1
This works:
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);
}
}
Solution 2
Check out this interesting solution!
List<string> files = new List<string>(System.IO.Directory.GetFiles(strDirLocalt));
files.ForEach(x => { try { System.IO.File.Delete(x); } catch { } });
Feel the beauty of the language!
Solution 3
Simply place a try/catch around the File.Delete because there could be more files that are in use which will also throw exceptions.
try
{
File.Delete(filePath);
}
catch (Exception ignore)
{
}
Solution 4
string[] filePaths = Directory.GetFiles(strDirLocalt);
foreach (string filePath in filePaths)
try {
File.Delete(filePath);
}
catch{ }
}
Author by
llk
Updated on June 22, 2022Comments
-
llk almost 2 years
I am having trouble deleting everything in a directory except a file (index.dat) I am trying to clear the cookies folder and the temp folder of files but I get an error when I try to delete index.dat because its being used by another process. Is there a way to delete everything in the temp and cookies folder except the index.dat file? Here is my code:
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);
-
Jon about 13 yearsIf you were to apply this more generically, it would be a pain to modify the list of files which are to be skipped. If you were to use the where-not style, it may save you time in the future to put all skipped files into a static array, then use
filePaths.Where(fp=>!skipped.Any(s=>fp.Contains(s)))
... -
Adi about 13 yearsThis is good. Anyway, you still need to loop through files, so I would combine the 2 solution: tster's and Hams's
-
Pol about 13 yearsYou're welcome :-) I modified it slightly to use FileInfo class.
-
llk about 13 yearsThis worked too. Thanks! It grabs any file that is currently "in use" too and blocks it from being deleted.
-
Nickon about 11 yearsLambdas make this lang pleasure to use:)
-
Pierre over 4 yearsinstead of
Directory.GetFiles(strDirLocalt)
usenew DirectoryInfo(strDirLocalt).GetFiles()
which returnsList<FileInfo>
then you can just dofi.Delete();
-
Alex from Jitbit over 2 yearsGood answer but leaves empty directories