private static void CopyDir(string path, string newpath)
{
try
{//检查目标目录是否以目录分割字符结束如果不是则添加之
if (newpath[newpath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
newpath += System.IO.Path.DirectorySeparatorChar;
}
//判断目标目录是否存在如果不存在则创建之
if (!System.IO.Directory.Exists(newpath))
{
System.IO.Directory.CreateDirectory(newpath);
}
//得到源目录的文件列表,该里面是包含文件及目录路径的一个数组
//如果指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] filelist=Directory.GetFiles(path)
string[] filelist = System.IO.Directory.GetFileSystemEntries(path);
//遍历所有的文件和目录
foreach (string item in filelist)
{
//先当作目录处理如果存在这个目录就递归copy该目录下面的文件
if (System.IO.Directory.Exists(item))
{
CopyDir(item, newpath + System.IO.Path.GetFileName(item));
}
//否则直接copy文件
else
{
System.IO.File.Copy(item, newpath + System.IO.Path.GetFileName(item), true);
}
}
}
catch (Exception)
{
throw;
}
}
从网易博客(http://cxwstar.blog.163.com/blog/static/48468763201142905746906/)迁移,原发表于2011年5月29日.