-1

I have folder with these files:

  • image1.png
  • image2.png
  • image3.png
  • image4.png
  • image5.png

And I need to check is exists extraneous files in this folder, for example if I create example.file.css I need to give an error, there must be only that files which listed above. So i've created needed files string:

string[] only_these_files = { 
    "image1.png", 
    "image2.png", 
    "image3.png",
    "image4.png",
    "image5.png"
};

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

Dewagg
  • 145
  • 10

2 Answers2

2

Use Directory.GetFiles: https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx

And compare with your list of allowed files.

    string[] only_these_files = { 
        "image1.png", 
        "image2.png", 
        "image3.png",
        "image4.png",
        "image5.png"
    };
    string[] fileEntries = Directory.GetFiles(targetDirectory);

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

    foreach (string fileName in fileEntries)
        if (!only_these_files.Contains(fileName))
        {
            badFiles.Add(fileName);
        }
Jonas
  • 185
  • 12
0

This would be my implementation with the use of a lil' LINQ

        var onlyAllowedFiles = new List<string>
        { 
            "image1.png", 
            "image2.png", 
            "image3.png",
            "image4.png",
            "image5.png"
        };

        var path = "";
        var files = Directory.GetFiles(path);

        var nonAllowedFiles = files.Where(f => onlyAllowedFiles.Contains(f) == false);

Or alternatively if you wish to only detect the presence of illegal files.

        var errorState = files.Any(f => onlyAllowedFiles.Contains(f) == false);
Daniel Varab
  • 223
  • 1
  • 10
  • Thank you, how can I check it now? I'm tried something like this: if(errorState == true){MessageBox.Show("Please delete non allowed files!");} And it's not worked for me – Dewagg Jul 10 '15 at 12:54
  • Why post a duplicate answer..? – Jonas Jul 10 '15 at 12:57
  • @Jonas Was fiddling with it while you answered. Non-intentional, rly. However I guess my solution is slighty different. @Dewagg you'll need to replace the path variable with the directory which you are inspecting - as like `var path = @"C:\the\path\to\your\directory"` – Daniel Varab Jul 10 '15 at 13:01