
如何复制一个目录里面的所有目录和文件
1个回答
展开全部
下面介绍几个我们在该例程中将要使用的类:
1、Directory:Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
2、Path:Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
3、File:Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
这两个类里都是不可继承的,是从object直接继承来的,被实现成sealed,上面的解释均来自MSDN。
下面是实现的代码,代码中的细节不在这里详细描述,请看代码注释:
// ======================================================
// 实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面
// ======================================================
public static void CopyDir(string srcPath,string aimPath){
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
// 遍历所有的文件和目录
foreach(string file in fileList){
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if(Directory.Exists(file))
// 否则直接Copy文件elseFile.Copy(file,aimPath+Path.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询