开发者

C# - Check filename ends with certain word

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 开发者_JAVA百科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?


Try:

Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜