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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With