C# - Regex for file paths e.g. C:\test\test.exe

68,017

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:

Win Regex

Unix Regex

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,})

Share:
68,017

Related videos on Youtube

Dan
Author by

Dan

Updated on July 09, 2022

Comments

  • Dan
    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
      cordsen almost 13 years
      Can you post what you have tried so far and some samples of input and expected output?
    • agent-j
      agent-j almost 13 years
      Do you need to support UNC paths like \\server\share\file.txt?
    • ulrichb
      ulrichb almost 13 years
      the regex C:\\test\\test2\\test\.exe validates your path.
  • Random Developer
    Random Developer almost 13 years
    59 seconds before my answer of the same thing, Bump for speed!
  • Dan
    Dan almost 13 years
    Could you provide a validation example please?
  • Dan
    Dan almost 13 years
    Thanks, remember to souce where you get stuff from ;)
  • agent-j
    agent-j almost 13 years
    @Dan. Wrote it for my own edification. Fun!
  • Random Developer
    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.i‌​ni"))) { /*Directory exists and valid*/ }
  • Jānis Gruzis
    Jānis Gruzis almost 11 years
    Does not work for \\test\test$\TEST.xls - problem with $ character probably there are other bad cases.
  • agent-j
    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é
    Junior Mayhé over 9 years
    Your 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
    Umesh almost 9 years
    correction - have to remove " otherwise throws error while using
  • Eirik H
    Eirik H over 8 years
    This 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
    Good Night Nerd Pride about 8 years
    This 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, and file://name for all occurences of name the same rules apply (i.e. name cannot contain any of the characters in \/:*?<>"|.
  • maddisoj
    maddisoj almost 8 years
    To be pedantic: characters 0 through to 32 are also not allowed.
  • raythurnevoid
    raythurnevoid over 7 years
    This 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
    John Demetriou about 7 years
    what about relatives paths?
  • John Demetriou
    John Demetriou about 7 years
    what 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
    Gabriel Marius Popescu almost 7 years
    The 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
    Herb almost 7 years
    @JohnDemetriou, a valid point. The "A:-Z:|\\ServerName" prefix would be needed to be made optional.
  • Renan Degrandi
    Renan Degrandi almost 7 years
    Your expression will not work if your path has ".", example: "C:\folder.folder\folder.txt"
  • Bogdan Popa
    Bogdan Popa over 6 years
    could you please also make an edit for paths like ~/ ?
  • raythurnevoid
    raythurnevoid over 6 years
    @BogdanPopa Done! :)
  • Dai
    Dai over 2 years
    The 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 or FileInfo.TryParse method which avoids exceptions entirely. Another reason is if you're using a debugger then every time Path's constructor throws an ArgumentException the debugger will break - and while you can opt to not break on ArgumentException it doesn't let you ignore only ArgumentException thrown from Path - so if you're SOL if you need to break elsewhere.
  • Jay
    Jay over 2 years
    Pasting this into Regex101 throws un-escaped delimiter errors.
  • Jay
    Jay over 2 years
    This expression incorrectly validates `\\192.168.0.1\INVALID SHARE` The share name cannot include spaces in UNC paths.