Exclude certain file extensions when getting files from a directory

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.


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

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

I know, this a old request, but about me it's always important.

if you want exlude a list of file extension: (based on https://stackoverflow.com/a/19961761/1970301)

var exts = new[] { ".mp3", ".jpg" };



public IEnumerable<string> FilterFiles(string path, params string[] exts) {
    return
        Directory
        .GetFiles(path)
        .Where(file => !exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}

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"))