How do I check for illegal characters in a path?

Mike Pateras picture Mike Pateras · Mar 12, 2010 · Viewed 61.3k times · Source

Is there a way to check if a String meant for a path has invalid characters, in .Net? I know I could iterate over each character in Path.InvalidPathChars to see if my String contained one, but I'd prefer a simple, perhaps more formal, solution.

Is there one?

I've found I still get an exception if I only check against Get

Update:

I've found GetInvalidPathChars does not cover every invalid path character. GetInvalidFileNameChars has 5 more, including '?', which I've come across. I'm going to switch to that, and I'll report back if it, too, proves to be inadequate.

Update 2:

GetInvalidFileNameChars is definitely not what I want. It contains ':', which any absolute path is going to contain ("C:\whatever"). I think I'm just going to have to use GetInvalidPathChars after all, and add in '?' and any other characters that cause me problems as they come up. Better solutions welcome.

Answer

Jeremy Bell picture Jeremy Bell · Mar 12, 2010

InvalidPathChars is deprecated. Use GetInvalidPathChars() instead:

    public static bool FilePathHasInvalidChars(string path)
    {

        return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);
    }

Edit: Slightly longer, but handles path vs file invalid chars in one function:

    // WARNING: Not tested
    public static bool FilePathHasInvalidChars(string path)
    {
        bool ret = false;
        if(!string.IsNullOrEmpty(path))
        {
            try
            {
                // Careful!
                //    Path.GetDirectoryName("C:\Directory\SubDirectory")
                //    returns "C:\Directory", which may not be what you want in
                //    this case. You may need to explicitly add a trailing \
                //    if path is a directory and not a file path. As written, 
                //    this function just assumes path is a file path.
                string fileName = System.IO.Path.GetFileName(path);
                string fileDirectory = System.IO.Path.GetDirectoryName(path);

                // we don't need to do anything else,
                                    // if we got here without throwing an 
                                    // exception, then the path does not
                                    // contain invalid characters
            }
            catch (ArgumentException)
            {
                                    // Path functions will throw this 
                                    // if path contains invalid chars
                ret = true;
            }
        }
        return ret;
    }