3

I have a folder, and a list (which contain file names). I want the program delete files except the file which are listed. C#

I hope it is possible.

Now used code:

It delete only ONE file.

        string folder = Directory.GetCurrentDirectory();
        string thisNOdelete = "example.exe";
        string[] list = Directory.GetFiles(@folder);//
        foreach (string file in list)
        {

            if (file.ToUpper().Contains(thisNOdelete.ToUpper()))
            {
                    //if found this do nothing

            }
            else
            {

               File.Delete(file);
            }
        }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
GaboO
  • 51
  • 1
  • 8

2 Answers2

6

You could try,

    public void DeleteFilesExcept(string directory,List<string> excludes)
    {
        var files = System.IO.Directory.GetFiles(directory).Where(x=>!excludes.Contains(System.IO.Path.GetFileName(x)));
        foreach (var file in files)
        {
            System.IO.File.Delete(file);
        }
    }
Mat J
  • 5,422
  • 6
  • 40
  • 56
0

I assume you are having files not to be deleted as a List of String,

 string[] filePaths = Directory.GetFiles(strDirLocalt);
    foreach (string filePath in filePaths)
    {
        var name = new FileInfo(filePath).Name;
        name = name.ToLower();
        foreach (var file in YourFileslist)
        {
            if (name != file)
            {
                File.Delete(filePath);
            }
        }
    }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396