将文件从一个位置复制到另一位置 [英] copy files from one location to another

查看:91
本文介绍了将文件从一个位置复制到另一位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建目录和子目录,并将文件从一个位置复制到另一位置.以下代码有效,但如果有子目录,则不会创建父目录(10_new).我正在尝试将所有内容(包括子目录)从"c:\\ sourceLoc \\ 10" 复制到"c:\\ destLoc \\ 10_new" 文件夹中.如果"10_new" 不存在,那么我应该创建此文件夹.请协助.

I am trying to create a directory and subdirectories and copy files from on one location to another location. The following code works but it doesn't create a parent directory(10_new) if there are sub directories. I am trying to copy all the contents(including subdirectories) from "c:\\sourceLoc\\10" to "c:\\destLoc\\10_new" folder. If "10_new" doesn't exist then I should create this folder. Please assist.

string sourceLoc = "c:\\sourceLoc\\10";
string destLoc = "c:\\destLoc\\10_new";

foreach (string dirPath in Directory.GetDirectories(sourceLoc, "*", SearchOption.AllDirectories))
{
    Directory.CreateDirectory(dirPath.Replace(sourceLoc, destLoc));
    if (Directory.Exists(sourceLoc))
    {
         //Copy all the files
         foreach (string newPath in Directory.GetFiles(sourceLoc, "*.*", SearchOption.AllDirectories))
             File.Copy(newPath, newPath.Replace(sourceLoc, destLoc));
    }
}

推荐答案

通过查看代码,您永远不会检查父文件夹是否存在.您将跳转到首先获取所有子文件夹.

From looking at your code, you never check for the existence of the parent folders. You jump to getting all the child folders first.

if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir");

这篇关于将文件从一个位置复制到另一位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆