Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET How to check if path is a file and not a directory?

I have a path and I need to determine if it is a directory or file.

Is this the best way to determine if the path is a file?

string file = @"C:\Test\foo.txt";  bool isFile = !System.IO.Directory.Exists(file) &&                           System.IO.File.Exists(file); 

For a directory I would reverse the logic.

string directory = @"C:\Test";  bool isDirectory = System.IO.Directory.Exists(directory) &&                              !System.IO.File.Exists(directory); 

If both don't exists that then I won't go do either branch. So assume they both do exists.

like image 959
David Basarab Avatar asked Jan 13 '09 15:01

David Basarab


People also ask

How do you tell if a path is a file or directory?

When you get a string value for a path, you can check if the path represents a file or a directory using Python programming. To check if the path you have is a file or directory, import os module and use isfile() method to check if it is a file, and isdir() method to check if it is a directory.


Video Answer


1 Answers

Use:

System.IO.File.GetAttributes(string path) 

and check whether the returned FileAttributes result contains the value FileAttributes.Directory:

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)                  == FileAttributes.Directory; 
like image 100
Alnitak Avatar answered Sep 22 '22 08:09

Alnitak