C#文件文件夹拖拽功能的实现
2015-04-02 09:34
429 查看
//--------------------文件拖拽处理,获取所有文件名----------------------------- using System.Windows.Forms /// <summary> /// 文件拖进事件处理: /// 获取数据源的链接Link /// </summary> public void dragEnter(DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) //判断拖来的是否是文件 e.Effect = DragDropEffects.Link; //是则将拖动源中的数据连接到控件 else e.Effect = DragDropEffects.None; }
/// <summary> /// 文件放下事件处理: /// 放下, 另外需设置对应控件的 AllowDrop = true; /// 获取的文件名形如 "d:\1.txt;d:\2.txt" /// </summary> public string dragDrop(DragEventArgs e) { string filesName = ""; Array file = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖来的数据转化为数组存储 //判断是否为目录,从目录载入文件 if (file.Length == 1) { string str = file.GetValue(0).ToString(); if (!System.IO.File.Exists(str) && System.IO.Directory.Exists(str)) //拖入的不是文件,是文件夹 { string[] files = System.IO.Directory.GetFiles(str); for (int i = 0; i < files.Length; i++) filesName += (files[i] + (i == files.Length - 1 ? "" : ";")); return filesName; } } //拖入的所有文件 int len = file.Length; for (int i = 0; i < len; i++) { filesName += (file.GetValue(i).ToString() + (i == file.Length - 1 ? "" : ";")); } return filesName; }
//文件拖拽示例: //拖拽文件到窗体Form1,获取拖入的所有文件名,Form1上包含一个ListBox1 //设置Form1.AllowDrop属性为true //--------------------为Form添加文件拖拽处理逻辑---------------------------------------- /// <summary> /// 文件或文件夹拖入 /// </summary> private void Form1_DragEnter(object sender, DragEventArgs e) { dragEnter(e); }
/// <summary> /// drop时,获取拖入的文件名 /// </summary> private void Form1_DragDrop(object sender, DragEventArgs e) { string filesName = T.dragDrop(e); <span style="white-space:pre"> </span>//拖入窗体的文件放下 string OpendFilesName = filesName.Split(';'); <span style="white-space:pre"> </span>//分割为所有的文件名 if (listBox1.Items.Count > 0) listBox1.Items.Clear(); //清空列表 foreach(string file in OpendFilesName) { String name = System.IO.Path.GetFileName(file); //获取文件名 listBox1.Items.Add(name); //添加文件名到列表 } }
相关文章推荐
- WinForm实现简单的拖拽文件到出题的功能(C#)(3)
- C#实现本地复制文件或者文件夹建立副本取名功能
- C#之winform实现文件拖拽功能
- C#窗体实现文件拖拽功能
- 简单的实现对话框中文件的拖拽功能
- C#使用XmlEDocument实现数据文件安全存储功能
- C#动态修改文件夹名称(FSO实现,不移动文件)
- C#实现外部图片的拖拽到应用程序的简单功能,附全部源码,供有需要的参考
- c# 实现文件浏览功能
- c# winform TreeView控件中实现拖拽的功能
- C#使用XmlEDocument实现数据文件安全存储功能
- C#语言实现创建、删除和移动文件夹及其文件夹列表功能
- 关于Windows下文件及文件夹扫描的简单实现(C#与C++)
- asp.net(c#)实现文件上传功能
- c#实现复制全部文件夹及文件的代码
- c#实现将一个文件夹中的所有文件复制到另一个文件夹,并在新文件夹中创建一个txt文件记录copy的文件综述以及文件名称
- winform(C#)拖拽实现获得文件路径
- 为 FCKeditor 增加删除文件和文件夹的功能(C#)
- 【Vegas改编】用C#实现浏览文件夹功能
- C#实现树型结构TreeView节点拖拽的简单功能,附全部源码,供有需要的参考