Jorge Rangel
Jorge Rangel

Reputation: 7

Find a folder with a partial name C#

I have a folder with a lot of projects, each folder is named in the same way:

8 characters + "space" + the name of the project

Example: 1234568 (Name of the project)

I am making a little GUI where I ask only the first 8 numbers of the project to open the corresponding folder.

So my question is....

Is there a way to search for this folder WITHOUT reading all the folders aside?

I was using this command Process.Start(@"C:\Projects\12345678 Example"); but this one requires the exact folder name.

I am looking something like this Process.Start(@"c:\Projects\12345678","*"); but so far I have not been able to do it

Upvotes: 0

Views: 818

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

You can use a search pattern in Directory.GetDirectories method:

var dirs = Directory.GetDirectories(mainProjectsPath, "12345678*");

Notice the * in the second parameter, which specifies to look for each directory whose name start with the value you provide. You can of course build this pattern dynamically using string interpolation:

var projectNamePrefix = "1234567";
var dirs = Directory.GetDirectories(mainProjectsPath, $"{projectNamePrefix}*");

This will return an array of directory paths, if you are only interested in one directory, you can use FirstOrDefault() method to get it.

Upvotes: 1

Related Questions