file – C# – Check filename ends with certain word – Education Career Blog

Hi I would like to know how to validate a filename in C# to check that it ends with a certain word (not just contains but is located at the end of the filename)

e.g I want to modify certain files that end with the suffix Supplier so I want to validate each file to test if it ends with Supplier, so LondonSupplier.txt, ManchesterSupplier.txt and BirminghamSupplier.txt would all be validated and return true but ManchesterSuppliers.txt wouldn’t.

is this even possible? I know you can validate a filename to test for a certain word anywhere within a filename but is it possible to do what i’m suggesting?





if (myFileName.EndsWith(“whatever”))
// Do stuff


By utilizing the System.IO.Path.GetFileNameWithoutExtension(string) method, you can extract the filename (sans extension) from a string. For example, calling it with the string C:\svn\trunk\MySourceFile.cs would return the string MySourceFile. After this, you can use the String.EndsWith method to see if your filename matches your criteria.


Linq solution:

    var result = FilePaths.Where(name => Path.GetFileNameWithoutExtension(name).EndsWith("Supplier"))
                      .Select(name => name).ToList();

Assuming that FilePaths is a list containing all the paths.

Leave a Comment