c# get path - How do I drag and drop files into an application?

4 Answers

Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...

controls windows listbox

I've seen this done in Borland's Turbo C++ environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

Here is something I used to drop files and/or folders full of files. In my case I was filtering for *.dwg files only and chose to include all subfolders.

fileList is an IEnumerable or similar In my case was bound to a WPF control...

var fileList = (IList)FileList.ItemsSource;

See https://.com/a/19954958/492 for details of that trick.

The drop Handler ...

  private void FileList_OnDrop(object sender, DragEventArgs e)
    var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));
    var files = dropped.ToList();

    if (!files.Any())

    foreach (string drop in dropped)
      if (Directory.Exists(drop))
        files.AddRange(Directory.GetFiles(drop, "*.dwg", SearchOption.AllDirectories));

    foreach (string file in files)
      if (!fileList.Contains(file) && file.ToLower().EndsWith(".dwg"))

The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):