Search code examples
c#filedetect

C# is exists unallowed files


I have folder with these files:

  • file1.exe
  • file2.dll

I want to check is exists extraneous files in this folder. For example if I create examplefile.exe in this folder it must give me an error, there must be only that files which listed above. So i've created needed files string:

string[] only_these_files = { 
    "file1.exe", 
    "file2.dll"
};

Now I need to search for extraneous files, but how to? Thanks immediately.

I'm tried this code, but I don't know how to check it.

string[] only_these_files = { 
            "image1.png", 
            "image2.png", 
            "image3.png",
            "image4.png",
            "image5.png"
        };
        string[] fileEntries = Directory.GetFiles(@"C:\Users\Dewagg\Desktop\test\");

        List<String> badFiles = new List<string>();

        foreach (string fileName in fileEntries)
            if (!only_these_files.Contains(fileName))
            {
                badFiles.Add(fileName);
            }

Solution

  • It's not exactly rocket science: something like this would do you:

    HashSet<string> allowedFiles = new HashSet<string>( StringComparer.OrdinalIgnoreCase )
    {
      "file1.exe" ,
      "file2.dll" ,
    };
    DirectoryInfo directory = new DirectoryInfo( @"c:\foo\bar" ) ;
    
    bool containsNonAllowedFiles = directory
                                   .EnumerateFiles( @"C\foo\bar" )
                                   .Any( fi => !allowedFiles.Contains( fi.Name ) )
                                   ;
    bool containsAllAllowedFiles = allowedFiles
                                   .All( fn => directory.EnumerateFiles( fn ).Any() )
                                   ;