Wednesday, March 16, 2011

Test for a syntactically correct path

In .NET is there a function that tests if a string is syntactically a correct path? I specifically don't want it to test if the path actually exists.

my current take on this is a regex:

([a-zA-Z]:|\\)?\\?([^/\\:*?"<>|]+[/\\])*[^/\\:*?"<>|]*

matches:

c:\
bbbb
\\bob/john\
..\..\

rejects:

xy:
c:\\bob
From stackoverflow
  • I'd suggest just using a regex for this since you specifically don't want to test if the path exists.

    Here's something google helped me dig up:

    RegEx="^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.[^\/\\:*?"<>|]+)$"
    

    You could combine this with System.IO.Path.GetInvalidPathChars() method and make the regex dynamically exclude all of the invalid characters.

    BCS : WT.. is that escaped for? I'm not able to make heads or tails of it.
  • You might be able to use System.IO.Path and the GetInvalidPathChars() function?

  • I believe System.IO.Path.GetFullPath(path) will throw an exception if it is not a syntactically correct path without checking to see if it exists.

    BCS : If that works, nice, but the fail case is just as valid for me as the pass case do I'd rather not throw/catch.
    Aaron Palmer : Yeah, could be what is needed. Here's the msdn: http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx From the article,"However, if path does exist, the caller must have permission to obtain path information for path." Could throw a wrench in depending on the situation.

0 comments:

Post a Comment