Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
.NET 7.0 (C#)

@"
(?=^.{1,80}$)(^[^\p{C}<>+=;,*?\\\/\[\]\:\|""]+$)
"
gs

Description

There are specific requirements for the different components of a UNC path. While it's possible to try and validate the entire UNC path in one go, you quite often end up needing to break the path down anyway unless simply handing it off to some other library (in which case they should be providing validation for you!) and it's a lot simpler to validate the components individually.

Unfortunately, there can be quite a lot of flexibility with UNC paths, and Microsoft's Type Definition only goes so far, as it says that the format can depend on the protocol.

Thier type definition says that a share name must be 1-80 characters long, and the allowed characters are (hexidecimal ASCII/Unicode/UTF-8) x20-21, x23-29, x2B-2E, x30-39, x40-5A, x5E-7B, and x7D-FF. Careful observers may note that this actually includes some non-printable characters, notably x7F, the Delete code. I haven't had a chance to test whether you can actually create a share that includes it though.

My use case is UNC for SMB/CIFS, so I checked the SMB/CIFS protocol definitions and they refer back to the UNC definition, but also the Microsoft File System Control Codes definition for share names. Rather than listing what is allowed, it lists what is illegal, however they equate to exactly the same. It specifically says "All other Unicode characters are legal".

Therefore, I've taken an approach of firstly looking ahead to count the characters - you may want to remove this group from the RegEx if you check the length prior, and then checking the list of non-allowed characters, including all control codes. This may not be quite right according to the standards, however it is practical.

Submitted by thejamesdecker - 2 years ago