Tuntuni
Tuntuni

Reputation: 491

How do I support dragging and dropping a folder in Winforms?

I would like to know how to Drag and Drop a folder and get its name. I already know how to do it with a file, but I'm not really sure how to modify it to be able to drag folders as well. Here's the code of the event that is triggered when a file is dropped:

private void checkedListBox_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        // NB: I'm only interested in the first file, even if there were
        // multiple files dropped
        string fileName = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
    }
}

Upvotes: 1

Views: 12045

Answers (1)

user7116
user7116

Reputation: 64148

You could test if the path is a folder and in your DragEnter handler, conditionally change the Effect:

 void Target_DragEnter(object sender, DragEventArgs e)
 {
     DragDropEffects effects = DragDropEffects.None;
     if (e.Data.GetDataPresent(DataFormats.FileDrop))
     {
         var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
         if (Directory.Exists(path))
             effects = DragDropEffects.Copy;
     }

     e.Effect = effects;
 }

Upvotes: 9

Related Questions