C # - checking the file name ends with a specific word

Hi, I would like to know how to check a file name in C # to check that it ends with a specific word (not only contains, but is at the end of the file name)

For example, I want to change some files that end with a Suffix Provider, so I want to check each file to see if it ends with a Provider, so LondonSupplier.txt, ManchesterSupplier.txt and BirminghamSupplier.txt will be checked and returned true but ManchesterSuppliers.txt will not be.

Is it even possible? I know that you can check the file name to check for a specific word anywhere in the file name, but is it possible to do what I suggest?

+3
source share
4 answers

Try:

Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")
+16
source

if (myFileName.EndsWith ("whatever")) {// Make The Material}

+1
source

Using the method System.IO.Path.GetFileNameWithoutExtension(string), you can extract the file name (sans extension) from the string. For example, calling it with the string C: \ svn \ trunk \ MySourceFile.cs will return the string MySourceFile. After that, you can use the method String.EndsWithto find out if your name meets your criteria.

+1
source

Linq Solution:

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

Assuming FilePaths is a list containing all paths.

0
source

Source: https://habr.com/ru/post/1770703/


All Articles