How do I distinguish a file or a folder in a drag and drop event in c#?
if(Directory.Exists(path))
// then it is a directory
else
// then it is a file
Given the path as a string, you can use System.IO.File.GetAttributes(string path) to get the FileAttributes
enum, and then check if the FileAttributes.Directory
flag is set.
To check for a folder in .NET versions prior to .NET 4.0 you should do:
FileAttributes attr = File.GetAttributes(path);
bool isFolder = (attr & FileAttributes.Directory) == FileAttributes.Directory;
In newer versions you can use the HasFlag
method to get the same result:
bool isFolder = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
Note also that FileAttributes
can provide various other flags about the file/folder, such as:
FileAttributes.Directory
: path represents a folderFileAttributes.Hidden
: file is hiddenFileAttributes.Compressed
: file is compressedFileAttributes.ReadOnly
: file is read-onlyFileAttributes.NotContentIndexed
: excluded from indexing
etc.