C#文件文件夹拖拽功能的实现

来源:互联网 发布:淘宝网积分怎么用 编辑:程序博客网 时间:2024/06/06 05:58

在界面中添加一个TextBox控件,或其他支持拖拽属性的控件。

属性:


事件:


private void Form_DragEnter(object sender, DragEventArgs e){    dragEnter(e);}private void Form_DragDrop(object sender, DragEventArgs e){    TextBox textBox = sender as TextBox;    textBox.Text = dragDrop(e);}/// <summary>/// 文件拖进事件处理:/// </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){    StringBuilder filesName = new StringBuilder("");    Array file = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖来的数据转化为数组存储    foreach (object I in file)    {        string str = I.ToString();        System.IO.FileInfo info = new System.IO.FileInfo(str);        //若为目录,则获取目录下所有子文件名        if ((info.Attributes & System.IO.FileAttributes.Directory) != 0)        {            str = getAllFiles(str);            if (!str.Equals("")) filesName.Append((filesName.Length == 0 ? "" : ";") + str);        }        //若为文件,则获取文件名        else if (System.IO.File.Exists(str))            filesName.Append((filesName.Length == 0 ? "" : ";") + str);    }    return filesName.ToString();}/// <summary>/// 判断path是否为目录/// </summary>public bool IsDirectory(String path){    System.IO.FileInfo info = new System.IO.FileInfo(path);    return (info.Attributes & System.IO.FileAttributes.Directory) != 0;}/// <summary>/// 获取目录path下所有子文件名/// </summary>public string getAllFiles(String path){    StringBuilder str = new StringBuilder("");    if (System.IO.Directory.Exists(path))    {        //所有子文件名        string[] files = System.IO.Directory.GetFiles(path);        foreach (string file in files)            str.Append((str.Length == 0 ? "" : ";") + file);        //所有子目录名        string[] Dirs = System.IO.Directory.GetDirectories(path);        foreach (string dir in Dirs)        {            string tmp = getAllFiles(dir);  //子目录下所有子文件名            if (!tmp.Equals("")) str.Append((str.Length == 0 ? "" : ";") + tmp);        }    }    return str.ToString();}

0 0
原创粉丝点击