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

两盒软妹~` 提交于 2019-12-03 12:40:02

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.

if fileName is a directory you can create a DirectoryInfo object and loop through all files (and subdirs)

you can have a look at this code:

http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx

(you dont need to use a DirectoryInfo object, you can also use the static methods from the Directory class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!