Exclude certain file extensions when getting files from a directory

Viewed 76014

How to exclude certain file type when getting files from a directory?

I tried

var files = Directory.GetFiles(jobDir);

But it seems that this function can only choose the file types you want to include, not exclude.

9 Answers

You should filter these files yourself, you can write something like this:

    var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));

You could try something like this:

  var allFiles = Directory.GetFiles(@"C:\Path\", "");
  var filesToExclude = Directory.GetFiles(@"C:\Path\", "*.txt");
  var wantedFiles = allFiles.Except(filesToExclude);

I guess you can use lambda expression

var files = Array.FindAll(Directory.GetFiles(jobDir), x => !x.EndWith(".myext"))

Afaik there is no way to specify the exclude patterns. You have to do it manually, like:

string[] files = Directory.GetFiles(myDir);
foreach(string fileName in files)
{
    DoSomething(fileName);
}

i used that

Directory.GetFiles(PATH, "*.dll"))

and the PATH is:

public static string _PATH = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Related