共实这是一个递归调用的问题.很简单,代码如下:
public void CopyDirectory( string sourceDirName, string destDirName)
{
try
{
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
File.SetAttributes(destDirName, File.GetAttributes(sourceDirName));
}
if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)
destDirName = destDirName + Path.DirectorySeparatorChar;
string[] files = Directory.GetFiles(sourceDirName);
foreach (string file in files)
{
if(File.Exists(destDirName + Path.GetFileName(file)))
continue;
File.Copy(file, destDirName + Path.GetFileName(file),true);
File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
total++;
}
string[] dirs = Directory.GetDirectories(sourceDirName);
foreach (string dir in dirs)
{
CopyDirectory(dir, destDirName + Path.GetFileName(dir));
}
}
catch (Exception ex)
{
StreamWriter sw = new StreamWriter(Application.StartupPath+"\\log.txt",true);
sw.Write(ex.Message+" "+DateTime.Now+"\r\n");
sw.Close();
}
}