11.17. Verifying a Path

Problem

You have a path—possibly entered by the user—and you need to verify that it has no illegal characters and that a filename and extension exist.

Solution

We use several of the static fields and methods in the Path class. We begin by writing a method called CheckUserEnteredPath, which accepts a string containing a path entered by the user and a Boolean value to decide whether we want to find all illegal characters or just the occurrence of any illegal character. Just finding any illegal character is much faster if you don’t care which illegal characters are present. This method first calls another method, either FindAnyIllegalChars or FindAllIllegalChars, each of which are described later in the Solution. If there are no illegal characters in this path, it is then checked for the existence of a file and extension:

public bool CheckUserEnteredPath(string path, bool any)
{
    try
    {
        Console.WriteLine("Checking path {0}",path);
        bool illegal = false;
        // two ways to do the search, one more expensive than the other...
        if(any == true)
            illegal = FindAnyIllegalChars(path);
        else
            illegal = FindAllIllegalChars(path);

        if (!illegal)
        {
            if (Path.GetFileName(path).Length == 0)
            {
                Console.WriteLine("A filename must be entered");
            }    
            else if (!Path.HasExtension(path))
            {
                Console.WriteLine("The filename must have an extension");
            }
            else
            {
                Console.WriteLine("Path is correct");
                return (true);
            }
        }
    }
    catch(Exception e)
    {    
        Console.WriteLine(e.ToString( ));
    }
    return (false);
}

The FindAllIllegalChars ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.