Recipe12.17.Verifying a Path


Recipe 12.17. Verifying a Path

Problem

You have a pathpossibly entered by the userand you need to verify that it has no illegal characters and that a filename and extension have been provided.

Solution

We use several of the static fields and methods in the Path class. We begin by writing a method called CheckUserEnteredPath, as shown in Example 12-5. It 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 presence of a filename and extension.

Example 12-5. CheckUserEnteredPath method

 public static bool CheckUserEnteredPath(string path, bool any) {     try     {         Console.WriteLine("Checking path {0}",path);         // Verify that the path parameter is not null.         if (path == null)         {             throw (new ArgumentNullException("path",                                              "The path passed in cannot be null"));         }         bool illegal = false;         List<char> invalidChars = new List<char>();         // Two ways to do the search, one more expensive than the other…         if(any == true)             illegal = FindAnyIllegalChars(path);    // Cheap         else             invalidChars = FindAllIllegalChars(path);   // Expensive         if (!illegal && invalidChars.Count == 0)         {             // Now make sure the path is not an empty string             // and its filename has an extension.             if (Path.GetFileName(path).Length == 0)             {                 Console.WriteLine("A file name must be entered");             }             else if (!Path.HasExtension(path))             {                 Console.WriteLine("The file name must have an extension");             }             else             {                 Console.WriteLine("Path is correct");                 return (true);             }         }         else if (invalidChars.Count > 0)         {             foreach(char c in invalidChars)                 Console.WriteLine(c);         }     }     catch(Exception e)     {         Console.WriteLine(e.ToString());     }         return (false); } 

The FindAllIllegalChars method, which is shown in Example 12-6 and which is called by the CheckUserEnteredPath method, accepts a string containing a path. This path is checked for illegal characters by using the IndexOfAny method on the string class. The IndexOfAny method finds the first occurrence of one of the characters supplied to it in the string being examined. This method uses the Path.InvalidPathChars static field to determine if any illegal characters exist in this path.

Example 12-6. FindAllIllegalChars method

 private static List<char> FindAllIllegalChars(string path) {     // Get directory portion of the path.     string dirName = path;     string fullFileName = "";     int pos = path.LastIndexOf( Path.DirectorySeparatorChar);     if (pos >= 0)     {         dirName = path.Substring(0, pos);         // Get filename portion of the path.         if (pos >= 0 && (pos + 1) < path.Length)             fullFileName = path.Substring(pos + 1);     }     int invalidCharPos = 0;     bool endOfPath = false;     List<char> invalidChars = new List<char>();     // Find any characters in the directory that are illegal.     while (!endOfPath)     {         invalidCharPos = dirName.IndexOfAny(Path.GetInvalidPathChars(),         invalidCharPos++);         if (invalidCharPos == -1)         {             endOfPath = true;         }         else         {             Console.WriteLine(                 "Invalid char {0} found at position {1} in directory path.",                                dirName[invalidCharPos], invalidCharPos);             invalidChars.Add(dirName[invalidCharPos]);             if (invalidCharPos >= dirName.Length - 1)             {                 endOfPath = true;             }             else             {                 invalidCharPos++;             }         }     }     bool endOfFileName = false;     invalidCharPos = 0;     // Find any characters in the filename that are illegal.     while (!endOfFileName)     {         invalidCharPos = fullFileName.IndexOfAny(Path.GetInvalidFileNameChars(),                                                  invalidCharPos++);         if (invalidCharPos == -1)         {             endOfFileName = true;         }         else         {             Console.WriteLine(                 "Invalid char {0} found at position {1} in file name.",                 fullFileName[invalidCharPos], invalidCharPos);             invalidChars.Add(fullFileName[invalidCharPos]);             if (invalidCharPos >= fullFileName.Length - 1)             {                 endOfFileName = true;             }             else             {                 invalidCharPos++;             }         }     }     return (invalidChars); } 

Notice that we did not use the Path.GetDirectoryName and Path.GetFileName methods to parse the directory and filename, respectively, from the entire path string. If we did use these methods on a path string containing invalid characters, they would throw an exception too early in the processing.

The FindAnyIllegalChars method shown in Example 12-7, which is also called by the CheckUserEnteredPath method, accepts a string containing a user-entered path. This path is checked for the existence of any illegal characters by using the IndexOfAny method on the string class. If the IndexOfAny method finds anything, we have an illegal path and we return false.

Example 12-7. FindAnyIllegalChars method

 private static bool FindAnyIllegalChars(string path) {     // Get directory portion of the path.     string dirName = path;     string fullFileName = "";     int pos = path.LastIndexOf(Path.DirectorySeparatorChar);     if (pos >= 0)     {         dirName = path.Substring(0, pos);         // Get filename portion of the path.         if (pos >= 0 && (pos + 1) < path.Length)             fullFileName = path.Substring(pos + 1);     }     // Find any characters in the directory that are illegal.     int invalidCharPos = dirName.IndexOfAny(Path.GetInvalidPathChars());     if (invalidCharPos == -1)     {         // Find any characters in the filename that are illegal.         invalidCharPos = fullFileName.IndexOfAny(Path.GetInvalidFileNameChars());         if (invalidCharPos == -1)         {             return (false);         }         else         {             Console.WriteLine(                 "Invalid char {0} found at position {1} in filename.",                 fullFileName[invalidCharPos], invalidCharPos);             return (true);         }     }     else     {             Console.WriteLine(                 "Invalid char {0} found at position {1} in directory path.",                 dirName[invalidCharPos], invalidCharPos);             return (true);     } } 

Discussion

This recipe provides a way of screening a path for invalid characters before it can be used in your application. This recipe does not verify that the directory or path exists; use the Directory.Exists or File.Exists methods to perform this verification.

The CheckUserEnteredPath method starts by calling the FindAnyIllegalChars or FindAllIllegalChars methods and passing the chosen one a path string. The path is validated against the set of characters supplied by both the Path.GetInvalidPathChars and the Path.GetInvalidFileNameChars static methods. These methods return character arrays that contain all of the invalid characters that could be entered into a path or filename string, respectively.

The CheckUserEnteredPath and FindAnyIllegalChars methods return true if there are illegal characters found. FindAnyIllegalChars prints information to the console for only the first one found, whereas FindAllIllegalChars returns a List<char> containing all illegal characters found.

See Also

See the "String Class" and "Path Class" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net