Question

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);
            }
        }
Was it helpful?

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

OTHER TIPS

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);
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top