How to distinguish a file or folder from a drag event in C #?

I have a form in which you drag and drop files, and I was wondering how I can get the application to find out if the data is a file or folder.

My first attempt was to search for "." in the data, but then in some folders there. in them. I also tried to fulfill the condition File.Exists and Directory.Exists, but then it searches only the current path of the application, and not anywhere else.

In any case, can I somehow apply .Exists in a specific directory, or is there a way to check which data types are being dragged into the form?

+10
c # file directory folder drag-and-drop
source share
2 answers

Given a path as a string, you can use System.IO.File.GetAttributes (string path) to get the FileAttributes enumeration, and then check if the FileAttributes.Directory flag is FileAttributes.Directory .

To check the folder in .NET versions prior to .NET 4.0, you must 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); 

Also note that FileAttributes can provide various other file / folder flags, such as:

  • FileAttributes.Directory : the path represents the folder
  • FileAttributes.Hidden : file is hidden
  • FileAttributes.Compressed : file compressed
  • FileAttributes.ReadOnly : read-only file
  • FileAttributes.NotContentIndexed : excluded from indexing

etc.

+17
source share
 if(Directory.Exists(path)) // then it is a directory else // then it is a file 
+1
source share

All Articles