Drag and Drop a Folder from Windows Explorer to listBox in C#

brat4hart picture brat4hart · Aug 25, 2011 · Viewed 15.8k times · Source

I succeeded in developing C# code for drag files from windows explorer to listBox.

    // Drag and Drop Files to Listbox
    private void listBox1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            e.Effect = DragDropEffects.All;
        else
            e.Effect = DragDropEffects.None;
    }

    private void listBox1_DragDrop(object sender, DragEventArgs e)
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
        foreach (string fileName in files)
        {
           listBox1.Items.Add(fileName);  
        }
    }

If I drag a folder to the listBox, all the files which are inside the folder to be added to the listBox items.

It would be very helpful to me if anybody can provide me the code snippet for the above task.

Thanks in advance.

Answer

Zodman picture Zodman · Jul 26, 2012

Your code for DragEnter still applies for folders.

In the DragDrop event, you retrieve filepaths and folder paths in the same way. If you drag combinations of files and folders, they will all show up in your files array. You just need to determine if the paths are folders or not.

The following code will retrieve all the paths of all files from the root of all folders dropped, and the paths of all files dropped.

    private void listBox1_DragDrop(object sender, DragEventArgs e)
    {
        List<string> filepaths = new List<string>();
        foreach (var s in (string[])e.Data.GetData(DataFormats.FileDrop, false))
        {
            if (Directory.Exists(s))
            {
                //Add files from folder
                filepaths.AddRange(Directory.GetFiles(s));
            }
            else
            {
                //Add filepath
                filepaths.Add(s);
            }
        }
    }

Note that only the files in the root of the folders dropped will be collected. If you need to get all files in the folder tree, you'll need to do a bit of recursion to collect them all.