Exclude certain file extensions when getting files from a directory

后端 未结 10 1926
一个人的身影
一个人的身影 2020-12-02 22:00

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

I tried

var files = Directory.GetFiles(jobDir);
相关标签:
10条回答
  • 2020-12-02 22:37

    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>();
    
    0 讨论(0)
  • 2020-12-02 22:38

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 22:38
    string[] filesToDelete = Directory.GetFiles(@"C:\Temp", "*.der");
    
    foreach (string fileName in filesToDelete)
    {
        File.Delete(fileName);
    }
    
    0 讨论(0)
  • 2020-12-02 22:40

    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)));
    }
    
    0 讨论(0)
  • 2020-12-02 22:51

    You could try something like this:

      var allFiles = Directory.GetFiles(@"C:\Path\", "");
      var filesToExclude = Directory.GetFiles(@"C:\Path\", "*.txt");
      var wantedFiles = allFiles.Except(filesToExclude);
    
    0 讨论(0)
  • 2020-12-02 22:52

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

        var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));
    
    0 讨论(0)
提交回复
热议问题