Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate folder name in C#

Tags:

c#

regex

I need to validate a folder name in c#.

I have tried the following regex :

 ^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$

but it fails and I also tried using GetInvalidPathChars().

It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername

Can anyone suggest why?

like image 936
Nida Sahar Avatar asked Oct 02 '12 10:10

Nida Sahar


3 Answers

You could do that in this way (using System.IO.Path.InvalidPathChars constant):

bool IsValidFilename(string testName)
{
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
    if (containsABadCharacter.IsMatch(testName) { return false; };

    // other checks for UNC, drive-path format, etc

    return true;
}

[edit]
If you want a regular expression that validates a folder path, then you could use this one:

Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");

[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:

var invalidPathChars = Path.GetInvalidPathChars(path)

or (for files):

var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)

like image 60
Nickon Avatar answered Sep 21 '22 13:09

Nickon


Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.

like image 30
slugster Avatar answered Sep 20 '22 13:09

slugster


this is regex you should use :

Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
    MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    metrotxtFolderName.Focus();
}
like image 29
phuc.nx Avatar answered Sep 19 '22 13:09

phuc.nx