简体   繁体   中英

Check if a folder exists with only a part of the name in C#

I have created a code to create folders with two Textboxes.

  • Textbox1 - customer number (XXXX).
  • Textbox2 - customer name.

I would like to be able to check if the customer number exists before creating the folder. The newly created folder will be the combination of the two Textboxes (this is already solved). I just need to be able to determine if the folder exists only with the customer number, as it is probably created with (customer number + customer name).

string[] dirs = Directory.GetDirectories(@"c:\",  txtTextBox.Text + "*");

this will only get directrories starting with the desired Text

Edit: This is only a good solution if the customer number has fixed places (in you exaple 4 from 0000-9999)

Microsoft Documentation - check example below

You could also each time you need the folder just do that:

    public static void Main()
    {
        var username = "someuser";
        var usernumber = "ABC123";
        var mainDirectory = @"C:\Path\To\The\Main\Dir";
        var pathToTheUserDirectory = Path.Combine(mainDirectory, $"{username}-{usernumber}");

        // This line will create the directory if not exist or take the existing directory.
        var directoryInfo = Directory.CreateDirectory(pathToTheUserDirectory);

        var directoryPath = directoryInfo.FullName;

        // ...  
        // or
        // directoryInfo.Delete(recursive: true);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM