惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
博客园 - 司徒正美
罗磊的独立博客
D
Docker
Last Week in AI
Last Week in AI
爱范儿
爱范儿
M
MIT News - Artificial intelligence
V
V2EX
Google DeepMind News
Google DeepMind News
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
Microsoft Security Blog
Microsoft Security Blog
T
Tailwind CSS Blog
MyScale Blog
MyScale Blog
V
Visual Studio Blog
博客园 - 叶小钗
B
Blog RSS Feed
A
About on SuperTechFans
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
P
Proofpoint News Feed

博客园 - DinoSaur

监测磁盘文件是否被修改程序 这两天随便写了个基类库 C#使用Jmail组件发送邮件 解决需求工程中的基本问题 如何编写用户操作手册 什么是软件需求 string.Equals(string)和==的原理 DataGrid格式 微软程序员测试题 C#中调用Windows API的要点 网站间共享数据的WebService 使用ASP.NET实现饼图 前台对象的事件一览 剖析ASP.NET下部构造 常用的DOCUMENT.EXECCOMMAND VS.NET下web项目源代码管理 DotNet向数据库中添加图片 DataGrid应用样式文件定义动态样式 C#编码标准--编码习惯
如何将一个目录里面的所有文件复制到目标目录里面。
DinoSaur · 2004-11-25 · via 博客园 - DinoSaur
 

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

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

1DirectoryExposes static methods for creating, moving, and enumerating through directories and subdirectories.

2PathPerforms operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.

3FileProvides 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);

}

}