paxcow
paxcow

Reputation: 1941

Searching a directory, excluding a list of certain file extensions

I am using the following line of code to get a list of all the files under an entered path:

Files = Directory.GetFiles(path, ".", SearchOption.AllDirectories);

However, what I want to do is, rather than getting all files, I want to exclude any that have certain file extensions. I am reading the list of file extensions to ignore from a text file which has one file extension per line (".pdf", ".dll", etc). I am using the following code to load the list of file extensions to ignore from the text file:

  ArrayList line = new ArrayList();
  using (StreamReader reader = new StreamReader(Server.MapPath("~/TextFile.txt")))
  {
      while (!reader.EndOfStream)
      {
          line.Add(reader.ReadLine());
      }
   }

My question is, how do I now limit my file search to not include any files that match any of those file extensions? I don't want to add those types of files into my Files string array.

Upvotes: 1

Views: 2363

Answers (4)

Steven Doggart
Steven Doggart

Reputation: 43743

You cannot specify a list of file extensions to exclude, so you will just have to get the full list and filter them out yourself. For instance, something like this should work:

List<string> fileExtensionsToIgnore = new List<String>(File.ReadAllLines("~/TextFile.txt"));
List<string> fileList = new List<string>();
foreach (string filePath in Directory.GetFiles(Path, ".", SearchOption.AllDirectories))
{
    if (!fileExtensionsToIgnore.Contains(Path.GetExtension(filePath).ToLower())
        fileList.Add(filePath);
}
string[] files = fileList.ToArray();

Upvotes: 1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Files = Directory.GetFiles(path, ".", SearchOption.AllDirectories)
.Where(fileName => !line.Contains(Path.GetExtension(fileName))
.ToList();

Upvotes: 3

lc.
lc.

Reputation: 116538

Reading into your question a bit, the answer is no, I don't believe there's an "easy" way to do what you want.

You'll have to read all the filenames first, and manually filter based on their extension (see System.IO.Path.GetExtension].

Upvotes: 1

slawekwin
slawekwin

Reputation: 6310

check the extension before adding to arraylist:

string file = reader.ReadLine();
if (!stringArrayWithExtensions.Contains(Path.GetExtension(file).ToLower()))
    line.Add(file);

Upvotes: 2

Related Questions