32

Following my scenario.

I got an Application which loads a Filestructure (Folders, Files) from a Database into a WPF ListView. Now I'd like to grab a file from this ListView, drag it over my Desktop (or some open explorer window) and drop it there. Basic Drag and Drop, nothing fancy. This sounds like a "standard" function for a windows application - but google won't help.

So how can I achieve this? Interops?

Thanks

Edit: Thanks for the solution, I still had to do some googling. Here's my complete solution.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Dänu
  • 5,791
  • 9
  • 43
  • 56
  • 1
    it would be appreciated if you posted your complete solution as an answer here. – H H Sep 10 '11 at 15:12
  • 1
    I tried your example but it wont compile, DragDrop is unknown. Do I need to add a reference or something ? – GuidoG Nov 03 '15 at 10:52

1 Answers1

30

DragDrop.DoDragDrop can do this as long as you pass it an appropriate DataObject.

First copy the files somewhere. You can use System.IO.Path.GetTempPath() if you don't have anywhere better.

Next create a string array containing the full paths to the files and do the following:

string[] paths = ...;
DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, paths),
                    DragDropEffects.Copy); 

It is actually possible to do this without pre-copying the files but that gets into some complicated IDataObject interactions, so unless your files are potentially very large and aren't already in the filesystem I would try this method first.

Gleno
  • 16,621
  • 12
  • 64
  • 85
Ray Burns
  • 62,163
  • 12
  • 140
  • 141
  • 4
    I know this is a very old thread, but could you expand on your statement about "unless your files are potentially very large"-part? I'm trying to do exactly that. Have a DragDrop functionality, which downloads the file when dropping it somewhere. – Falgantil Apr 28 '15 at 07:11
  • How to do the same with DragAndDrop folders? – Argnist Sep 11 '15 at 03:48
  • @Argnist Same as files. Folder are treated as Files. – Aishwarya Shiva Sep 22 '15 at 19:49
  • @Ray-Burns Copying a large file to temp location might take a lot of time. Is there any other way to achieve this and resolve `IDataObject` interactions at the same time? Please have a look at my [Question Here](http://stackoverflow.com/questions/32725514/unable-to-drag-file-to-windows-explorer-from-a-wpf-listview) also. – Aishwarya Shiva Sep 22 '15 at 19:52
  • 1
    @AishwaryaShiva but they are not copied to explorer as files. I do DragDrop and nothing happens. – Argnist Sep 23 '15 at 11:05
  • 1
    @Ray-Burns where does the DragDrop object comes from ? I tried your example but DragDrop is not a know class. Do I need to add a reference ? – GuidoG Nov 03 '15 at 10:51
  • 2
    It should be noted that having the data in an array is crucial even if you have only one file! – TaW Jul 20 '17 at 08:18