C# filter file extensions

Markus Freitag 3,791 Reputation points
2022-04-28T08:57:22.36+00:00

Hello,

I have a folder with many files.
The files are structured as follows.
Name001.product
Name002.product
Name003.product
Name004.product
Name00n.product

Additionally
Name101.product.prototype
Name102.product.prototype
Name103.product.prototype.
Name104.product.prototype
Name10n.product.prototype

Is there a file filter that gives me only the files without prototype in a list?

*.product
delivers all.

Which query would work well here? I need only .product

not .product*

Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-04-28T09:34:34.507+00:00

    I created files as per

    string[] names = {
        "Name001.product",
        "Name002.product",
        "Name003.product",
        "Name101.product.prototype",
        "Name102.product.prototype",
        "Name103.product.prototype",
    };
    
    foreach (var name in names)
    {
        File.WriteAllText(name,"");
    }
    

    Then in another event

    Directory.GetFiles(
        AppDomain.CurrentDomain.BaseDirectory,"*.product")
        .ToList()
        .ForEach(Console.WriteLine);
    
    Console.WriteLine();
    
    Directory.GetFiles(
        AppDomain.CurrentDomain.BaseDirectory, 
        "*.product.prototype")
        .ToList()
        .ForEach(Console.WriteLine);
    

    Outputs

    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name001.product
    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name002.product
    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name003.product

    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name101.product.prototype
    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name102.product.prototype
    C:\Dotnetland\VS2019\ForumQuestion\Demo\bin\Debug\Name103.product.prototype

    I ran the above code with .NET Core 5 and .NET Framework 4.8, both yield the same output.

    Another example with a different pattern and predicate.

    Directory.GetFiles(
            AppDomain.CurrentDomain.BaseDirectory, "Name*.*")
        .Where(fileName => !fileName.EndsWith("prototype"))
        .ToList()
        .ForEach(Console.WriteLine);
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.