实现文件和文件夹的复制的方法

话不多说,请看代码:

01
private void btnSave_Click(object sender, EventArgs e) //文件复制、保存方法
02
{
03
#region 静态复制文件(写死)
04
string desPath = @“c:\1\1.chm”;
05
if (File.Exists(desPath))
06
{
07
//目标文件已存在
08
if (MessageBox.Show((“文件已存在,是否覆盖”), “询问”, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
09
== DialogResult.Yes) //选择Yes 确定覆盖
10
{
11
//复制文件
12
File.Copy(@“c:\ls\w3.chm”, desPath, true);
13
MessageBox.Show(“覆盖成功”);
14
}
15
}
16
else //文件不存在
17
{
18
//开始复制
19
File.Copy(@“c:\ls\w3.chm”, desPath, true);
20
MessageBox.Show(“复制成功”);
21
}
22
//显示打开对话框,返回值为dialogResult类型,如果是OK,则用户点击的为打开,否则为取消
23
openFileDialog1.InitialDirectory=(@“c:\1”); //选择文件时的默认位置
24
//openfilediaglog1.filter中的fileter是过滤器的作用
25
//showdialog()显示对话框的方法.
26
openFileDialog1.Filter = “可执行程序|.exe|TXT文本|.txt|图片文件|.jpg|所有文件|.*”;//可保存类型
27

28
if (openFileDialog1.ShowDialog() == DialogResult.OK)//点击了打开
29
{
30
if (saveFileDialog1.ShowDialog() == DialogResult.OK) //说明点yes 也就是确认保存
31
{
32
File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName, true);
33
MessageBox.Show(“保存完成”);
34
}
35
}
36
#endregion
37
}
38
//File类是对文件操作的,包括复制、保存、创建时间、修改时间等等等等。
39
//Directory功能类似file
40
#region 动态
41
private void btnCopyContents_Click(object sender, EventArgs e)
42
{
43
string oldDir, newDir; //分别是原文件夹和目标文件夹
44
FolderBrowserDialog sourceFolder = new FolderBrowserDialog();//动态生成了folderbrowserdialog这个控件 不需要拖控件
45
sourceFolder.Description = “请选择要复制的文件夹”;//显示了一个简单说明
46
if(sourceFolder.ShowDialog()DialogResult.OK)//点了确定
47
{
48
oldDir = sourceFolder.SelectedPath;
49
sourceFolder.Description = “请选择要复制到的文件夹”;//修改了一下sourcefolder的说明文字 便于使用者使用
50
if (sourceFolder.ShowDialog()
DialogResult.OK) //如果确定 那么执行下面代码块代码
51
{
52
newDir = sourceFolder.SelectedPath;
53
//获取当前要复制的文件夹中的所有文件(注意!不包含下级文件夹及其中的文件)
54
string[] files = Directory.GetFiles(oldDir);//定义了个字符数组来接收源文件内需要复制的文件
55
foreach (string filepath in files) //也可以用for语句
56
{
57
//File.Copy(filepath,newDir+"\"+filepath.Substring(filepath.LastIndexOf("\")+1),true);
58
//拆分了一下,更为简洁
59
string nFileName ; //定义一个string类型,来获取文件名
60
nFileName = filepath.Substring(filepath.LastIndexOf("\") + 1); //获取要复制的文件夹里的文件名
61
File.Copy(filepath, newDir + “\” + nFileName, true); //最后得出要复制的文件夹以及文件夹里的文件名并进行复制
62
}
63
//MessageBox.Show(“复制完成”);
64
}
65
//MessageBox.Show(sourceFolder.SelectedPath);
66

67
}
68
}
69
#endregion
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助

本文原创自news.mkq.online
版权声明:本文为原创文章,版权牛站新闻所有
转载请注明http://www.niuzhan.com/Bago/

猜你喜欢

转载自blog.csdn.net/weixin_44385859/article/details/86626574
今日推荐