55

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.

one noa
  • 345
  • 1
  • 3
  • 10
Graviton
  • 81,782
  • 146
  • 424
  • 602
  • Duplicate of this: http://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters – Rune Grimstad Apr 16 '09 at 08:15
  • Possible duplicate of [C# - Get a list of files excluding those that are hidden](http://stackoverflow.com/questions/2418270/c-sharp-get-a-list-of-files-excluding-those-that-are-hidden) – TarmoPikaro May 27 '16 at 05:35
  • 1
    @TarmoPikaro, I think it is another way round . Your question is a dupe of mine. – Graviton May 27 '16 at 09:15

9 Answers9

107

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

    var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));
okutane
  • 13,754
  • 10
  • 59
  • 67
  • As far as i now the EndsWith takes capital letters into account, which means that if the filetype would be .XML it would not exclude it. – Daniel Jørgensen Sep 27 '14 at 09:32
  • 4
    `var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml", true));` – doog abides Nov 08 '14 at 22:47
  • 4
    `var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));` – nothingisnecessary Oct 06 '17 at 14:08
  • 1
    Worked for me. I just had to add .ToList(); at the end because my variable was a list :) – M. Fawad Surosh Jan 10 '20 at 15:30
  • @m-fawad-surosh Thanks, good comment, I needed a slightly different variant, since the original `GetFiles` returns `string[]` and I wanted to keep my code with the same convention, I just did a call similar to: `Directory.GetFiles(jobDir).Where(...).ToArra()`, there are more such options! – Juv Feb 24 '21 at 11:26
  • Note that you can return a List if you use `.ToList()` method. Then, you'll have something like this: `List files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml")).ToList();` – Sergio Quinteiro Dec 26 '22 at 09:57
21

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)));
}
Dennis Meissel
  • 1,825
  • 1
  • 21
  • 33
pask23
  • 714
  • 11
  • 20
  • 1
    I was looking a LINQ way to exclude multiple extensions. I found it here. Thank you very much. – WpfBee May 11 '18 at 05:01
15

You could try something like this:

var allFiles = Directory.GetFiles(@"C:\Path\", "");
var filesToExclude = Directory.GetFiles(@"C:\Path\", "*.txt");
var wantedFiles = allFiles.Except(filesToExclude);
Julien Poulin
  • 12,737
  • 10
  • 51
  • 76
  • This works brilliantly in all forms of the GetFiles() command. It doesn't solve the question precisely but you get the added benefit of leveraging the searchPattern parameter, which is much more powerful than just looking at extensions. – w0rd-driven Jun 14 '12 at 18:30
  • 2
    Advice: this won't work with the instance method `DirectoryInfo.GetFiles()`: it returns an array of FileInfo (instead string), a non-comparable/non-equatable class. – T-moty Feb 13 '15 at 14:32
  • 1
    This solution is good for multi pattern file exclusion. Thanks – Abhay Feb 09 '19 at 16:03
11

I guess you can use lambda expression

var files = Array.FindAll(Directory.GetFiles(jobDir), x => !x.EndWith(".myext"))
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
oscarkuo
  • 10,431
  • 6
  • 49
  • 62
3

You can try this,

var directoryInfo = new DirectoryInfo("C:\YourPath");
var filesInfo = directoryInfo.GetFiles().Where(x => x.Extension != ".pdb");
mvk
  • 283
  • 1
  • 2
  • 8
0

This is my version on the answers I read above

List<FileInfo> fileInfoList = ((DirectoryInfo)new DirectoryInfo(myPath)).GetFiles(fileNameOnly + "*").Where(x => !x.Name.EndsWith(".pdf")).ToList<FileInfo>();
user3071434
  • 133
  • 1
  • 2
  • 13
0

I came across this looking for a method to do this where the exclusion could use the search pattern rules and not just EndWith type logic.

e.g. Search pattern wildcard specifier matches:

  • * (asterisk) Zero or more characters in that position.
  • ? (question mark) Zero or one character in that position.

This could be used for the above as follows.

string dir = @"C:\Temp";
var items = Directory.GetFiles(dir, "*.*").Except(Directory.GetFiles(dir, "*.xml"));

Or to exclude items that would otherwise be included.

string dir = @"C:\Temp";
var items = Directory.GetFiles(dir, "*.txt").Except(Directory.GetFiles(dir, "*HOLD*.txt"));
Woolly
  • 21
  • 3
0

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);
}
Biri
  • 7,101
  • 7
  • 38
  • 52
-2

i used that

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

and the PATH is:

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