O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required