tags:

views:

100

answers:

4

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?

+14  A: 

Try:

Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")
Pieter
+1: Dammit, I was outdrawn in TFGITW
Callum Rogers
Thanks a lot :)
Terry
You're welcome.
Pieter
Thought about accepting the answer?
Pieter
+1  A: 

if (myFileName.EndsWith("whatever")) { // Do stuff }

BaBu
+1  A: 

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.

Heini Høgnason
A: 

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.

Aamir