Search code examples
c#directorydelete-filegetfiles

Delete all in folder except the filename in list


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

Solution

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