Search code examples
c#.netwindowsregex

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


I am currently looking for a regex that can help validate a file path e.g.:

C:\test\test2\test.exe

Solution

  • 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.