ControlFileClass类中的CopyFile和MoveFile函数:
///
/// 移动文件
///
/// 文件原始路径
/// 文件目标路径
/// 文件名
public static void MoveFile(string dirPath, string tarPath, string name)
{
bool flag = false;
foreach (string d in Directory.GetFileSystemEntries(dirPath))
{
if (File.Exists(dirPath + @"\" + name))
{
flag = true;
}
}//end of for
if (!flag)
{
Console.WriteLine("目标文件 " + name + " 不存在");
return;
}
File.Move(dirPath + @"\" + name, tarPath + @"\" + name);
}//end of MoveFile
///
/// 复制文件
///
/// 文件原始路径
/// 文件目标路径
/// 文件名
public static void CopyFile(string dirPath, string tarPath, string name)
{
bool flag = false;
foreach (string d in Directory.GetFileSystemEntries(dirPath))
{
if (File.Exists(dirPath + @"\" + name))
{
flag = true;
}
}//end of for
if (!flag)
{
Console.WriteLine("目标文件 " + name + " 不存在");
return;
}
File.Copy(dirPath + @"\" + name, tarPath + @"\" + name);
}//end of CopyFile
简单的函数使用实例:
ControlFileClass.CopyFile(rootPath + @"\" + "wybnmsl", rootPath + @"\" + "moguwai", "1.txt");
ControlFileClass.MoveFile(rootPath + @"\" + "wybnmsl", rootPath + @"\" + "moguwai", "2.txt");
如果直接是控制台应用那么复制,剪切也就是移动,都比较好理解,因为直接当前路径和目标路径都知道了。但是在winform开发中,这就不一样了,因为在一个控件上点击复制或者剪切只知道当前路径,不知道目标路径的。那么这个时候就需要将这个copy和move过程分段,下面是一个实例:
在345文件夹下的时候,我点击item xxxxxxx.txt,此时我通过menupath记录下了点击事件时,listview中的item的路径
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
ContextMenuStrip menu = (ContextMenuStrip)sender;
ListView livi = (ListView)menu.SourceControl;
//ToolStripItem toolStripItem = (ToolStripItem)livi.SelectedIndices;
ListView.SelectedIndexCollection c = livi.SelectedIndices;
menupath = livi.FocusedItem.Tag.ToString();//记录下在哪个item下
//判断右键位置是否有item
if (c.Count > 0)
{
//有item就正常显示右键菜单
}
//没有item就没有反应
else
e.Cancel = true;
}
此时这个点击事件就为其右键菜单中的所有功能都记录下了这个menupath,那么接下来右键菜单(ToolStripMenuItem)中任何操作需要用到点击事件下对应的item的位置都可以了
比如剪切和复制,那么就是单纯的记录下menupath即可
private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
{
originpath = menupath;
if (ControlFileClass.IsFolder(menupath))
{
MessageBox.Show("不支持复制文件夹");
}
else
{
MessageBox.Show("复制文件成功");
}
COM = 1;
}
private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
{
originpath = menupath;
if (ControlFileClass.IsFolder(menupath))
{
MessageBox.Show("不支持剪切文件夹");
}
else
{
MessageBox.Show("复制剪切成功");
}
COM = 2;
}
然后在粘贴的时候,此时的menupath就是目标地址了,而originpath就是上面记录下的原始地址,此时就可以完成从原始地址到目标地址的移动或者复制
private void 粘贴ToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (!ControlFileClass.IsFolder(menupath))
{
MessageBox.Show("粘贴失败,粘贴目标应该为文件夹");
}
else
{
string filename = ControlFileClass.GetFileName(originpath);
originpath = ControlFileClass.GetFolderPath(originpath);
if (COM == 1)
{
ControlFileClass.CopyFile(originpath, menupath, filename);
COM = 0;
}
else if (COM == 2)
{
ControlFileClass.MoveFile(originpath, menupath, filename);
COM = 0;
}
else
{
MessageBox.Show("剪切板中没有任何文件");
}
}
知识库刷新(fenquname);
}