Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to check if a Path is a File or a Directory?

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?

like image 312
SnAzBaZ Avatar asked Sep 08 '09 17:09

SnAzBaZ


People also ask

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

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.

How do you tell if a file is a directory?

Instead, open() the file read-only first and use fstat() . If it's a directory, you can then use fdopendir() to read it. Or you can try opening it for writing to begin with, and the open will fail if it's a directory.

What is the difference between file path and directory?

A Directory is a disk file that contains reference information to other files. or in simple words, it is a folder. A Path is just a string wrapped in a Path Class in C# which facilitates us with many different conventions depending on the operation system.


2 Answers

From How to tell if path is file or directory:

// get the file attributes for file or directory FileAttributes attr = File.GetAttributes(@"c:\Temp");  //detect whether its a directory or file if ((attr & FileAttributes.Directory) == FileAttributes.Directory)     MessageBox.Show("Its a directory"); else     MessageBox.Show("Its a file"); 

Update for .NET 4.0+

Per the comments below, if you are on .NET 4.0 or later (and maximum performance is not critical) you can write the code in a cleaner way:

// get the file attributes for file or directory FileAttributes attr = File.GetAttributes(@"c:\Temp");  if (attr.HasFlag(FileAttributes.Directory))     MessageBox.Show("Its a directory"); else     MessageBox.Show("Its a file"); 
like image 51
Quinn Wilson Avatar answered Sep 22 '22 11:09

Quinn Wilson


How about using these?

File.Exists(); Directory.Exists(); 
like image 27
llamaoo7 Avatar answered Sep 23 '22 11:09

llamaoo7