Q:

Regex Directory Name Validation

I want to check if a textbox have a valid directory name. Because I will create a directory with this textbox value.
Another thing, the value must have at least 3 characters and cannot have more than 20 characters.
How can I do it?

A:

Path.GetInvalidPathChars is where you can find out which characters are invalid. Rather than use regex, I suggest you use Path.GetFullPath as this will validate the path for you: invariably it will do a better job than anything you will try to roll yourself and will be kept up-to-date as the rules change over time.
As for its length, use the methods of the Path class to get the component of the path that you want to check.

A:

No need for RegEx, it's a waste.
public bool ValidName(string dirName)
{
    char[] reserved = Path.GetInvalidFileNameChars();

    if (dirName.Length < 3)
         return false;
    if (dirName > 20)
         return false;

    foreach (char c in reserved)
    {
         if (dirName.Contains(c))
             return false;
    }

    return true;
}

RegEx isn't particularly efficient and isn't really necessary here. Just check the bounds then make sure the string doesn't contain any reserved characters, returning false as soon as you find an error.

