I am processing a TreeView
of directories and files. A user can select either a file or a directory and then do something with it. This requires me to have a method which performs different actions based on the user's selection.
At the moment I am doing something like this to determine whether the path is a file or a directory:
bool bIsFile = false;
bool bIsDirectory = false;
try
{
string[] subfolders = Directory.GetDirectories(strFilePath);
bIsDirectory = true;
bIsFile = false;
}
catch(System.IO.IOException)
{
bIsFolder = false;
bIsFile = true;
}
I cannot help to feel that there is a better way to do this! I was hoping to find a standard .NET method to handle this, but I haven't been able to do so. Does such a method exist, and if not, what is the most straightforward means to determine whether a path is a file or directory?
This was the best I could come up with given the behavior of the Exists and Attributes properties:
Here's how it tests out:
I needed this, the posts helped, this gets it down to one line, and if the path isn't a path at all, it just returns and exits the method. It addresses all of the above concerns, doesn't need the trailing slash either.
Maybe for UWP C#
This is using DirectoryInfo to get the attribute
This will work if you trying to get through DirectoryInfo trying to create a TreeView or read a TreeView
If you want to find directories, including those that are marked "hidden" and "system", try this (requires .NET V4):
soooo late in the game i know, but thought i'd share this anyway. If you are solely working with the paths as strings, figuring this out is easy as pie:
for example:
ThePath == "C:\SomeFolder\File1.txt"
would end up being this:Another example:
ThePath == "C:\SomeFolder\"
would end up being this:And this would also work without the trailing backslash:
ThePath == "C:\SomeFolder"
would end up being this:Keep in mind here that this only works with the paths themselves, and not the relationship between the path and the "physical disk"... so it can't tell you if the path/file exists or anything like that, but it sure can tell you if the path is a folder or a file...