C# - Regex for file paths e.g. C:\test\test.exe
Solution 1
I decided to post this answer which does use a regular expression.
^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$
Works for these:
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
Edit: Added example usage:
if (Regex.IsMatch (text, @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"))
{
// Valid
}
*Edit: * This is an approximation of the paths you could see. If possible, it is probably better to use the Path class or FileInfo class to see if a file or folder exists.
Solution 2
I would recommend using the Path class instead of a Regex if your goal is to work with filenames.
For example, you can call Path.GetFullPath to "verify" a path, as it will raise an ArgumentException
if the path contains invalid characters, as well as other exceptiosn if the path is too long, etc. This will handle all of the rules, which will be difficult to get correct with a Regex.
Solution 3
This is regular expression for Windows paths:
(^([a-z]|[A-Z]):(?=\\(?![\0-\37<>:"/\\|?*])|\/(?![\0-\37<>:"/\\|?*])|$)|^\\(?=[\\\/][^\0-\37<>:"/\\|?*]+)|^(?=(\\|\/)$)|^\.(?=(\\|\/)$)|^\.\.(?=(\\|\/)$)|^(?=(\\|\/)[^\0-\37<>:"/\\|?*]+)|^\.(?=(\\|\/)[^\0-\37<>:"/\\|?*]+)|^\.\.(?=(\\|\/)[^\0-\37<>:"/\\|?*]+))((\\|\/)[^\0-\37<>:"/\\|?*]+|(\\|\/)$)*()$
And this is for UNIX/Linux paths
^\/$|(^(?=\/)|^\.|^\.\.)(\/(?=[^/\0])[^/\0]+)*\/?$
Here are my tests:
These works with Javascript
EDIT I've added relative paths, (../, ./, ../something)
EDIT 2 I've added paths starting with tilde for unix, (~/, ~, ~/something)
Solution 4
The proposed one is not really good, this one I build for XSD, it's Windows specific:
^(?:[a-zA-Z]\:(\\|\/)|file\:\/\/|\\\\|\.(\/|\\))([^\\\/\:\*\?\<\>\"\|]+(\\|\/){0,1})+$
Solution 5
Try this one for Windows and Linux support: ((?:[a-zA-Z]\:){0,1}(?:[\\/][\w.]+){1,})
Related videos on Youtube
Dan
Updated on July 09, 2022Comments
-
Dan almost 2 years
I am currently looking for a regex that can help validate a file path e.g.:
C:\test\test2\test.exe
-
cordsen almost 13 yearsCan you post what you have tried so far and some samples of input and expected output?
-
agent-j almost 13 yearsDo you need to support UNC paths like
\\server\share\file.txt
? -
ulrichb almost 13 yearsthe regex
C:\\test\\test2\\test\.exe
validates your path.
-
-
Random Developer almost 13 years59 seconds before my answer of the same thing, Bump for speed!
-
Dan almost 13 yearsCould you provide a validation example please?
-
Dan almost 13 yearsThanks, remember to souce where you get stuff from ;)
-
agent-j almost 13 years@Dan. Wrote it for my own edification. Fun!
-
Random Developer almost 13 years@Dan here is an example, note that the path can be UNC or local: if(Directory.Exists(Path.GetDirectoryName(@"C:\Windows\win.ini"))) { /*Directory exists and valid*/ }
-
Jānis Gruzis almost 11 yearsDoes not work for \\test\test$\TEST.xls - problem with $ character probably there are other bad cases.
-
agent-j almost 11 years@janisCruzis, thanks for pointing out that case. I have improved my answer, though you are probably right about other edge cases.
-
Junior Mayhé over 9 yearsYour regular expression will NOT work if your path / filename contains blank spaces:
Regex.IsMatch(@"c:\your folder\sub folder\your file.txt", @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$")
-
Umesh almost 9 yearscorrection - have to remove " otherwise throws error while using
-
Eirik H over 8 yearsThis one worked better for me (detected all UNC paths I sent to it), but I'm not familiar enough with regex to know if the " should be removed or escaped (e.g. changed to "" for vb.net). I didn't actually see a difference in testing, the regex worked both ways.
-
Good Night Nerd Pride about 8 yearsThis fails for
C:/
(also with back slash). Fixed version:^(?:[A-Z]\:|\.|(?:file\:\/\/|\\\\)[^\\\/\:\*\?\<\>\"\|]+)(?:(?:\\|\/)[^\\\/\:\*\?\<\>\"\|]+)*(?:\\|\/)?$
. This one works under the assumption that in the cases\\name
,C:\name
, andfile://name
for all occurences ofname
the same rules apply (i.e.name
cannot contain any of the characters in\/:*?<>"|
. -
maddisoj almost 8 yearsTo be pedantic: characters 0 through to 32 are also not allowed.
-
raythurnevoid over 7 yearsThis would validate unvalid file paths as: \\, \\\, C:\a\\ and it doesn't validate these: C:, C:\folder.something, C:\.folder: regex101.com/r/7UgtQA/2/tests
-
John Demetriou about 7 yearswhat about relatives paths?
-
John Demetriou about 7 yearswhat if it is a relative path? e.g. starts with ..? btw I tried it and it only matches part of the path
-
Gabriel Marius Popescu almost 7 yearsThe pattern above lacks a '\' next too the '/' in order to be recognized as regex pattern. The pattern should look like: ((?:[a-zA-Z]\:){0,1}(?:[\\\/][\w.]+){1,})
-
Herb almost 7 years@JohnDemetriou, a valid point. The "A:-Z:|\\ServerName" prefix would be needed to be made optional.
-
Renan Degrandi almost 7 yearsYour expression will not work if your path has ".", example: "C:\folder.folder\folder.txt"
-
Bogdan Popa over 6 yearscould you please also make an edit for paths like ~/ ?
-
raythurnevoid over 6 years@BogdanPopa Done! :)
-
Dai over 2 yearsThe problem is that in some situations (esp. high-performance code) you really don't want to have to catch exceptions to validate user-input. It's disappointing that .NET doesn't have a
Path.TryParse
orFileInfo.TryParse
method which avoids exceptions entirely. Another reason is if you're using a debugger then every timePath
's constructor throws anArgumentException
the debugger will break - and while you can opt to not break onArgumentException
it doesn't let you ignore onlyArgumentException
thrown fromPath
- so if you're SOL if you need to break elsewhere. -
Jay over 2 yearsPasting this into Regex101 throws un-escaped delimiter errors.
-
Jay over 2 yearsThis expression incorrectly validates `\\192.168.0.1\INVALID SHARE` The share name cannot include spaces in UNC paths.