views:

31

answers:

1

I'm trying to verify that a filename and path input by the user is structurally correct in a C# GUI. I do not need to make sure the file exists, just that the name is a valid windows file name and the path is a valid relative path from the present working directory. Absolute paths must be explicitly denied. Regex was never my thing.

Accepted inputs would be:
"myfiles\mydocument.pdf"
"Another_folder\an0th3r_fi1e.fake"
".\folder\file.docx" (current directory designation)

Rejected inputs would be: "C:\anything"
"internal folder\files??*>\myfile.pdf"
"folder\file " (whitespace at beginning or end)
"....\folder located elsewhere\file.txt" (upward navigation)

Thanks for any help!

As a loose guide: MSDN 'Naming Files, Paths, and Namespaces'

A: 

Try this:

@"(\.\\)?([a-zA-Z0-9_-]+[.a-zA-Z0-9_-]*\\)*[a-zA-Z0-9_-]+[.a-zA-Z0-9_-]*"

Note that this is vulnerable to a DDOS attack.

SLaks
Thanks for that! I'm giving it a look over now; it seems to work for what I need. I appreciate the article. It was an interesting read.
Robolulz