9.13 Determine if a Path Is a Directory or a File


9.13 Determine if a Path Is a Directory or a File

Problem

You have a path (in the form of a string), and you want to determine whether it corresponds to a directory or a file.

Solution

Test the path with the Directory.Exists and the File.Exists methods .

Discussion

The System.IO.Directory and System.IO.File classes both provide an Exists method. The Directory.Exists method returns true if a supplied relative or absolute path corresponds to an existing directory. File.Exists returns true if the path corresponds to an existing file.

Using these two methods, you can quickly determine if a path corresponds to a file or directory, as shown here:

 using System; using System.IO; public class FileOrPath {     private static void Main(string[] args) {         foreach (string arg in args) {             Console.Write(arg);             if (Directory.Exists(arg)) {                 Console.WriteLine(" is a directory");             }             else if (File.Exists(arg)) {                 Console.WriteLine(" is a file");             }             else {                 Console.WriteLine(" does not exist");             }         }         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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