Check folder name in C #

I need to check the folder name in C #.

I tried the following regex:

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

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

It fails when I try to use P:\abc as the folder name ie Driveletter:\foldername

Can someone tell me why?

+6
source share
3 answers

You can do it this way (using the 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 the regular expression to check the folder path, you can use it:

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

[edit 2]
I remembered one difficult thing that allows you to check the correctness of the path:

var invalidPathChars = Path.GetInvalidPathChars(path)

or (for files):

var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)

+9
source

Validating the folder name can be quite an important task. See My Blog Taking Data Binding, Validation, and MVVM to the Next Level - Part 2 .
Do not be fooled by the header, it is about checking the paths of the file system and illustrates some of the difficulties associated with using the methods provided by .Net. Although you can use regex, this is not the most reliable way to do this job.

0
source

this is a regular expression that 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(); } 
-1
source

Source: https://habr.com/ru/post/926744/


All Articles