posted 7/16/2010 by Raghav Khunger
Today a person asked on the forums on how to check or determine whether the physical path he is having is a directory or a file. I told him the solution to go for FileAttributes.Directory property. If this property is true it means we are dealing with directory else with file. Below is the sample code:
#region Using Directives using System; using System.IO; #endregion public class Example { class Test { static void Main() { string path1 = @"D:\Foo\foo.txt"; string path2 = @"D:\Foo\"; bool isDirectory1 = (File.GetAttributes(path1) & FileAttributes.Directory) == FileAttributes.Directory; bool isDirectory2 = (File.GetAttributes(path2) & FileAttributes.Directory) == FileAttributes.Directory; Console.WriteLine(isDirectory1 ? string.Format("{0} is a directory.", path1) : string.Format("{0} is a file.", path1)); Console.WriteLine(isDirectory2 ? string.Format("{0} is a directory.", path2) : string.Format("{0} is a file.", path2)); Console.ReadLine(); } } }
Above I have taken two dummy paths to test . One is the file "D:\Foo\foo.txt" and the other is a directory "D:\Foo\" . Next with the help of "FileAttributes.Directory" property I have determined whether it is a file or a directory. Here is the output which I got when I run the above program.
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18