拖动并在C#中从Windows资源管理器拖放文件夹到列表框控件 [英] Drag and Drop a Folder from Windows Explorer to listBox in C#

查看:499
本文介绍了拖动并在C#中从Windows资源管理器拖放文件夹到列表框控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地开发了阻力文件的C#代码从Windows资源管理器列表框。

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.

先谢谢了。

推荐答案

您的代码的dragenter 仍然适用的文件夹。

Your code for DragEnter still applies for folders.

的DragDrop 事件,您检索以同样的方式文件路径和文件夹路径。如果您将文件和文件夹的组合,他们都将在你的文件阵列显示出来。你只需要确定路径的文件夹或没有。

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.

这篇关于拖动并在C#中从Windows资源管理器拖放文件夹到列表框控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆