Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I distinguish a file or a folder in a drag and drop event in c#?

I have a form that you drag and drop files into and I was wondering how can I make the application know if the data is a file or a folder.

My first attempt was to look for a "." in the data but then some folders do have a . in them. I've also tried doing a File.Exists and a Directory.Exists condition but then it only searches on the current application path and not anywhere else.

Is there anyway I can somehow apply the .Exists in a specific directory or is there a way I can check what type of data is dragged into the form?

like image 843
Raphael Avatar asked May 05 '11 06:05

Raphael


People also ask

What happens when you drag and drop a file?

By default, if you left-click and HOLD the left mouse or touchpad button while moving your mouse pointer to a different folder location on the same drive, when you release the left mouse button the file will be moved to the new location where you released the mouse button.

How do you drop and drag a file?

To drag and drop a file or folder, click it with your left mouse button, then, without releasing the button, drag it to the desired location and release the mouse button to drop it. Refer to your Windows help for more information if you haven't used drag and drop.

What is a drag and drop document?

HTML Drag and Drop interfaces enable web applications to drag and drop files on a web page. This document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page.


2 Answers

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 folder
  • FileAttributes.Hidden: file is hidden
  • FileAttributes.Compressed: file is compressed
  • FileAttributes.ReadOnly: file is read-only
  • FileAttributes.NotContentIndexed: excluded from indexing

etc.

like image 170
Groo Avatar answered Oct 10 '22 16:10

Groo


if(Directory.Exists(path))
  // then it is a directory
else
  // then it is a file
like image 45
Chuck Savage Avatar answered Oct 10 '22 18:10

Chuck Savage