MikeTWebb
MikeTWebb

Reputation: 9279

Regular expression to disallow special characters that are invalid in a Windows Folder name

I have a C# .Net MVC 3 web app. I am needing to decorate a property with a RegEx data annotation that conforms to the rules for a windows folder name. The invalid characters are: \, /, *, : , ? , “, <, >, |

I'm not a greate RegEx developer and I've tried a few RegEx's but they have all disallowed the - character which our app needs to allow.

I have tried:

^[a-zA-Z0-9]+(([_][a-zA-Z0-9])?[a-zA-Z0-9]*)*$

^[a-zA-Z''-'\s]{1,40}$

^( [a-zA-Z] )( ( [a-zA-Z_\-\s0-9\.\)\(] )( [^\\!@#$%^&/:*?<>""|]* ) )*$

Valid:

MyFilemane-!@#$%^&

Invalid:

MyFilename|
MyFileName\

Upvotes: 1

Views: 9203

Answers (2)

hwnd
hwnd

Reputation: 70732

You can do this without using regular expressions by using the following:

See the documentation, they give full examples of implementing these methods.

To check your path or filenames:

var invalidPath = Path.GetInvalidPathChars(path)
var invalidFN   = Path.GetInvalidFileNameChars(file)

I would implement the StringBuilder Class for doing this also.

If you are looking to do this using a regex, this should work for you.

^[a-zA-Z]+?[^\\\/:*?"<>|\n\r]+$

Upvotes: 4

MikeTWebb
MikeTWebb

Reputation: 9279

I found a resolution at the following web address RegEx for valid Windows Folder/File name

The Regex resolution is:

^[^\\\./:\*\?\""<>\|]{1}[^\\/:\*\?\""<>\|]{0,254}$

Which also applies the 255 character limitation requirement.

The resolution applied in MVC3 C# .Net Code. Title is a property of my C# class:

[Display(Name = "Title")]
[Required(ErrorMessage = "Title is required.")]
[RegularExpression(@"^[^\\\./:\*\?\""<>\|]{1}[^\\/:\*\?\""<>\|]{0,254}$", 
    ErrorMessage = @"The following special characters are not allowed: \ / * :  ?  "" < > | ")]
public virtual string Title { get; set; }

Upvotes: 1

Related Questions