复制文件夹下所有文件

复制文件夹下所有文件,以及目录结构;一个递归,其他没什么了,直接上代码吧

 1 private static bool CopyFile(string path,string newPath) {
 2             string[] di = Directory.GetDirectories(path);
 3             string[] fi = Directory.GetFiles(path);
 4 
 5             if (!Directory.Exists(newPath)) {
 6                 Directory.CreateDirectory(newPath);
 7             }
 8 
 9             for (int i = 0; i < fi.Length; i++)
10             {
11                 string name = fi[i].Substring(fi[i].LastIndexOf("\\") + 1);
12                 
13                 File.Copy(fi[i], newPath + "\\" + name,true);
14             }
15             foreach (string p in di)
16             {
17                 string ps = p.Substring(p.LastIndexOf("\\"));
18                 CopyFile(p, newPath+ps+"");
19             }
20             return true;
21         }

 我在这里针对上面的代码做一些修改,这要感谢我的一位开源中国的网友,是他提醒了我,这里我就直接引用他的话了

话说这行
string name = fi[i].Substring(fi[i].LastIndexOf("\\") + 1);
改为:string name = Path.GetFileName(fi[i]);
更好吧

stringps = p.Substring(p.LastIndexOf("\\"));
这个也类似

newPath + "\\" + name
这个也应改为System.IO.Path.Combine(newPath, name)
以支持跨平台

针对上面我写的代码,我表示很遗憾,这确实是一大失误,还需要好好学习

转载于:https://www.cnblogs.com/xufei/p/filecopy.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值