c# 实现文件拖入和拖出(拖拽)

摘自:http://www.cnblogs.com/eaglet/archive/2009/01/06/1370149.html

C# WinForm下一步一步实现文件的拖入和拖出

作者:Eaglet

在WinForm实现一个类似资源浏览器的功能,需要实现将WinForm中列出的文件拖出到其他应用程序中或者从其他应用程序中将文件拖入到Winform应用中。网上有一些文章介绍这种功能,但都比较零散,缺少一个完整的例子。为此我编写了一个较完整的实现文件拖入和拖出的例子,并撰写此文一步步讲解如果实现类似功能。

  • 步骤1 放置一个 ListView 到 Winform窗体中 并初始化如下属性:

listView.View = View.Details;
            listView.AllowDrop = true;

  •   步骤2 撰写一个目录文件列表显示的函数

/**//// <summary>
/// List files in the folder
/// </summary>
/// <param name="directory">the directory of the folder</param>
private void ListFolder(string directory)
{
            labelCurFolder.Text = directory;

            String[] fileList = System.IO.Directory.GetFiles(directory);
            listViewFolder.Items.Clear();
            listViewFolder.Columns.Clear();
            listViewFolder.Columns.Add("Name", 300);
            listViewFolder.Columns.Add("Size", 100);
            listViewFolder.Columns.Add("Time", 200);

foreach (string fileName in fileList)
{
//Show file name
                ListViewItem itemName = new ListViewItem(System.IO.Path.GetFileName(fileName));
                itemName.Tag = fileName;

//Show file icon

                IconImageProvider iconImageProvider = new IconImageProvider(listViewFolder.SmallImageList,

listViewFolder.LargeImageList);

                itemName.ImageIndex = iconImageProvider.GetIconImageIndex(fileName);

//Show file size
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
long size = fileInfo.Length;

                String strSize;
if (size < 1024)
{
                    strSize = size.ToString();
                }
else if (size < 1024 * 1024)
{
                    strSize = String.Format("{0:###.##}KB", (float)size / 1024);
                }
else if (size < 1024 * 1024 * 1024)
{
                    strSize = String.Format("{0:###.##}MB", (float)size / (1024 * 1024));
                }
else
{
                    strSize = String.Format("{0:###.##}GB", (float)size / (1024 * 1024 * 1024));
                }

                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                subItem.Text = strSize;
                subItem.Tag = size;
                itemName.SubItems.Add(subItem);

//Show file time
                subItem = new ListViewItem.ListViewSubItem();
                DateTime fileTime = System.IO.File.GetLastWriteTime(fileName);

                subItem.Text = (string)fileTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); ;
                subItem.Tag = fileTime;

                itemName.SubItems.Add(subItem);
                listViewFolder.Items.Add(itemName);
            }
        }

上面代码中有一段显示图标的代码由于和拖动无关,我就不贴出来了,感兴趣可以下载完整的代码去看。

  • 步骤3 为ListView 添加 DragEnter 事件

DragEnter 事件在其他应用程序拖入的文件进入时判断当前拖动的对象类型,如果是文件类型,则设置拖动响应类型为Copy.

private void listViewFolder_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
                e.Effect = DragDropEffects.Copy;
            }
else
{
                e.Effect = DragDropEffects.None;
            }

        }

  • 步骤4 为ListView 添加 DragDrop 事件

DragDrop 事件在这里完成将其他应用程序拖入的文件拷贝到Winform应用当前的目录中。

private void listViewFolder_DragDrop(object sender, DragEventArgs e)
{
try
{
                String[] files = e.Data.GetData(DataFormats.FileDrop, false) as String[];

//Copy file from external application
foreach (string srcfile in files)
{
string destFile = labelCurFolder.Text + "\\" + System.IO.Path.GetFileName(srcfile);
if (System.IO.File.Exists(destFile))
{

if (MessageBox.Show(string.Format(

"This folder already contains a file named {0}, would you like to replace the existing file",

System.IO.Path.GetFileName(srcfile)),

"Confirm File Replace", MessageBoxButtons.YesNo, MessageBoxIcon.None) !=

DialogResult.Yes)

{

continue;
                        }
                    }

                    System.IO.File.Copy(srcfile, destFile, true);
                }

//List current folder
                ListFolder();
            }
catch (Exception e1)
{
                MessageBox.Show(e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

  完成上述4步后,拖入功能就实现了。下面步骤完成拖出功能

  • 步骤5 为ListView 添加 ItemDrag 事件

   这个事件在ListView 的Item被拖动时响应,我们利用这个事件将当前选中的item对应的文件名复制到拖动数据中,

并调用窗体的DoDragDrop方法告知窗体现在开始做拖放操作。

private void listViewFolder_ItemDrag(object sender, ItemDragEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (listViewFolder.SelectedItems.Count <= 0)
{
return;
                }

//put selected files into a string array

string[] files = new String[listViewFolder.SelectedItems.Count];

int i = 0;
foreach (ListViewItem item in listViewFolder.SelectedItems)
{
                    files[i++] = item.Tag.ToString();
                }

//create a dataobject holding this array as a filedrop

                DataObject data = new DataObject(DataFormats.FileDrop, files);

//also add the selection as textdata

                data.SetData(DataFormats.StringFormat, files[0]);

//Do DragDrop
                DoDragDrop(data, DragDropEffects.Copy);
            }
        }
    }

时间: 2024-08-07 21:17:24

c# 实现文件拖入和拖出(拖拽)的相关文章

Dos 显示拖入文件全路径

@echo off ::文件路径 echo %~dp1 rem 文件名 echo %~nx1 %显示完整路径% echo %~dp1%~nx1 pause % set 命令: rem 拖入文件,回显路径 % set /p file=输入的值会赋给file:file= echo file=%file%

批处理获取拖入文件信息

@ECHO OFF echo %1:获取拖入文件完整路径.如:"E:\DDC\add.txt"echo %~1:获取拖入文件完整路径,并去掉首尾引号.如:E:\DDC\add.txtecho %~nx1:获取拖入文件文件名及后缀.如:add.txtecho %~n1:获取拖入文件文件名.如:addecho %~x1:获取拖入文件后缀名.如:.txtecho %~dp1:获取拖入文件所在目录完整路径.如:E:\DDC\echo %cd%:获取拖入文件所在目录路径.如:E:\DDCecho

关于air文件拖入加载解析的两个问题

因需用到拖入加载问价解析,于是第一感觉就是想到了air,经网上查到代码如下: public class Darg extends Sprite     {         public function Darg ()         {             if (stage) {                 creat();             }else{                 addEventListener(Event.ADDED_TO_STAGE,creat);

BMfont踩坑点之cocosStudio1.6版本BitmapLabel无法拖入制作好的fnt文件

cocosStudio加入了一个自定义字体BitmapLabel,但是拖入BMfont制作好的fnt文件却始终无法拖入,排除BMfont在制作fnt文件时有中文路径,以及导出的fnt文件和png不在同一目录下等因素,最终发现BMfont导出文件时,png图片会默认在命名后面加_0,从而导致cocosStudio无法使用fnt文件. 解决方法:先把导出的图片后的_0去掉,在把fnt文件编辑,里面的引用的图片名字同样去掉_0,cocosStudio便可使用. 原文地址:https://www.cnb

重写TreeView,多层级节点下批量显示图片,图片支持缩略图和文件名列表切换,支持调用者动态匹配选中,支持外界拖入图片并添加到对应节点下

原文:重写TreeView,多层级节点下批量显示图片,图片支持缩略图和文件名列表切换,支持调用者动态匹配选中,支持外界拖入图片并添加到对应节点下 1.先看下整体效果 2.前端代码 1 <UserControl x:Class="iPIS.UI.Base.Tree.ImageTreeControl" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x=&quo

Xcode中将图片放入Images.xcassets和直接拖入的区别

将图片放入Images.xcassets 在mainBundle里面Xcode会生成一个Assets.car文件,将我们放在Images.xcassets的图片打包在里面.(程序会变大(?)) 无论是通过imageNamed:来加载图片,还是直接在Storyboard的UIImageView里面设置图片,并且无论图片是jpg格式还是png格式,都不需要写后缀名. 放在Images.xcassets的图片不能通过imagesWithContentsOfFile:来加载.(因为这个方法相当于是去ma

firebug离线安装方法-拖入法

这里介绍的是如何在Firefox中离线安装firebug插件. 1, 下载firebug离线包, 一般就是一个*.xpi文件; 2, 打开Firefox浏览器,直接将*.xpi文件拖入Firefox浏览器即可完成安装. 附上 Firefox和firebug安装包下载地址(百度网盘) http://pan.baidu.com/s/15zqDS

TFS命令tf:undo(强制签入别人签出的文件)(转)

我们在使用TFS源代码管理的时候,会遇到这样的情况,源代码管理会在每个客户PC上创建一个工作区,然后这个工作区域映射到服务器上的源码文件夹,我们在正常签入,签出的时候,我们的源码会在服务器到客户端的工作区进行操作,但是一旦有项目组成员在告假或者离职之前签出,并且加入了签出锁,这时如果项目组的其他成员想要修改被锁定的文件,或者是TFS的管理员想要在源代码管理中删除这个项目,这时问题出现了,因为我们无法通过Team Explorer图形界面来进行撤出签出操作,只能通过TFS命令:undo来进行操作,

windows下编写的bash脚本拖入linux环境下脚本出错之编码问题

windows下编写的bash脚本拖入linux环境下脚本出错之编码问题         脚本经常在windows下写好,拖入到linux环境中运行.但是在运行过程中,经常出现编码问题,这里记录一下.方便自己日后查看,或者给刚好遇到这样的问题的同学一个尝试的方法. 在linux环境下vim 进入拖入的bash脚本.执行命令 :set ff=unix