Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if filename contains substring in C#

Tags:

c#

.net

I have a folder with files named

  1. myfileone
  2. myfiletwo
  3. myfilethree

How can I check if file "myfilethree" is present.

I mean is there another method other than IsFileExist() method, i.e like filename contains substring "three"?

like image 718
sreeprasad Avatar asked Sep 19 '11 12:09

sreeprasad


People also ask

How to check if a string contains a sub-string in C++?

Check if a string contains a sub-string in C++. Here we will see how the string library functions can be used to match strings in C++. Here we are using the find() operation to get the occurrences of the substring into the main string. This find() method returns the first location where the string is found.

How do you find the starting address of a substring?

The function takes two char pointer arguments, the first denoting the string to search in and the other denoting the string to search for. It finds the first starting address of the given substring and returns the corresponding pointer to char. If the substring is not found in the first argument string, the NULL pointer is returned.

What is a substring in Python?

A substring is itself a string that is part of a longer string. For example, substrings of string "the" are "" (empty string), "t", "th", "the", "h", "he" and "e."

How to match strings in C++?

Here we will see how the string library functions can be used to match strings in C++. Here we are using the find () operation to get the occurrences of the substring into the main string. This find () method returns the first location where the string is found. Here we are using this find () function multiple times to get all of the matches.


1 Answers

Substring:

bool contains  = Directory.EnumerateFiles(path).Any(f => f.Contains("three"));

Case-insensitive substring:

bool contains  = Directory.EnumerateFiles(path).Any(f => f.IndexOf("three", StringComparison.OrdinalIgnoreCase) > 0);

Case-insensitive comparison:

bool contains  = Directory.EnumerateFiles(path).Any(f => String.Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase));

Get file names matching a wildcard criteria:

IEnumerable<string> files = Directory.EnumerateFiles(path, "three*.*"); // lazy file system lookup

string[] files = Directory.GetFiles(path, "three*.*"); // not lazy
like image 103
abatishchev Avatar answered Oct 16 '22 16:10

abatishchev