Check the selected path is Directory or File using C#

By Jatin Prajapati

In this FAQ we will see how to check that the provided path is Directory or File using C#.

In some requirements we need to check that the provided path is actually a directory or file. So to check this we can use FileAttributes property of the FileInfo object or DirectoryInfo object. But by using these objects we need to check for two time. Rather we can directly get thie FileAttributes using GetAttributes method of File object. See the below example.


string path = @"C:\Program Files\Common Files\Microsoft Shared";
string path1 = @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ADMISAPI\admin.asmx";
FileAttributes fas = File.GetAttributes(path);
if(( fas & FileAttributes.Directory) == FileAttributes.Directory)
Console.WriteLine("Given path is directory");
else
Console.WriteLine("Given path is file");

fas = File.GetAttributes(path1);
if(( fas & FileAttributes.Directory) == FileAttributes.Directory)
Console.WriteLine("Given path is directory");
else
Console.WriteLine("Given path is file");

Check the selected path is Directory or File using C#  (1351 Views)