Delete everything in a directory except a file in C#

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);
    }
}

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!


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)
{
}