如何复制一个目录里面的所有目录和文件

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

本文介绍如何将一个目录里面的所有文件复制到目标目录里面。

下面介绍几个我们在该例程中将要使用的类:

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))

CopyDir(file,aimPath+Path.GetFileName(file));

// 否则直接Copy文件

else

File.Copy(file,aimPath+Path.GetFileName(file),true);

}

}

嘿嘿!这次给大家说的功能比较简单,适合初学者,希望对初学者有所帮助!如果你需要将该功能使用在Web工程中,那么请设置给ASPNET帐号足够的权限,不过这样做是很危险的,不建议这样做。

有什么疑问或者建议可以发送邮件到:wu_jian830@hotmail.com

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航