您的位置:首页 > 编程语言 > C#

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);                           //添加文件名到列表
            }
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: