-1

I have directories for example with this pattern:

  • 0001.MyFolder

  • 0002.MyFolder2

  • 0003.MyFolder3

Inputs is only number of directory ( example enter 0002 -> then get items in MyFolder 3)

and how to return path of directory by its number ? example : enter 0002 return C:\MyPath\0002.MyFolder2

The pattern is

Number (dot) String

So i need access any directory by the number before dot.

kokowawa
  • 35
  • 5
  • 2
    What have you tried, because this is not particularly hard, and there is no need for regex – TheGeneral Apr 25 '19 at 00:00
  • 1
    [`Directory.GetFiles`](https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.8) would be a relevant place to start. While a Regex can be used, it's not required. Also see [`Path.GetFileName`](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.8) and `String.StartsWith`, etc (remember that files are case-insensitive on Windows, although such is not relevant for numbers). I would probably use Single from LINQ for the filter as it'll trivially abort on 'oops' cases. – user2864740 Apr 25 '19 at 00:06
  • Possible duplicate of [Can you call Directory.GetFiles() with multiple filters?](https://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters) – peeyush singh Apr 25 '19 at 01:39

1 Answers1

3

The best approach for figuring out something, is to start googling and reading the documentation

GetDirectories(String, String)

Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.


searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in searchPattern.

Wildcard specifier Matches

  • * (asterisk) Zero or more characters in that position.
  • ? (question mark) Zero or one character in that position.

So here is a little method that can help you

  public string GetFolder(string index, string path)
     => Directory.GetDirectories(path, $"{index}.*")
                 .FirstOrDefault();

Usage

var dir = GetFolder("0001", @"C:\MyHomeWorkFolder");

if(dir != null)
   // we have found something
TheGeneral
  • 79,002
  • 9
  • 103
  • 141