.NET只提供了文件的Copy方法,但却没有提供文件夹的Copy方法,经过一天的努力,终于搞定.现贴出主要代码供大家参考,欢迎大家提出建议. 代码如下:
public int DirectoryName(string DirectoryPath)//获取文件夹名,截取“\”
{
int j = 0; char[] c = DirectoryPath.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)//从后面截取
{
j = i;
if (c[i] == '\\')
{
break;//遇"\"调处,并返回"\"的位置
}
}
return j+1;
}
public void CopyDirectory(string DirectoryPath,string DirAddress)//复制文件夹,
{
#region//递归
string s = DirectoryPath.Substring(DirectoryName(DirectoryPath));//获取文件夹名
if (Directory.Exists(DirAddress + "\\" + s))
{
Directory.Delete(DirAddress + "\\" + s,true);//若文件夹存在,不管目录是否为空,删除
Directory.CreateDirectory(DirAddress + "\\" + s);//删除后,重新创建文件夹
}
else
{
Directory.CreateDirectory(DirAddress + "\\" + s);//文件夹不存在,创建
}
DirectoryInfo DirectoryArray = new DirectoryInfo(DirectoryPath);
FileInfo[] Files = DirectoryArray.GetFiles();//获取该文件夹下的文件列表
DirectoryInfo[] Directorys = DirectoryArray.GetDirectories();//获取该文件夹下的文件夹列表
foreach (FileInfo inf in Files)//逐个复制文件
{
File.Copy(DirectoryPath + "\\" + inf.Name, DirAddress + "\\" + s + "\\" + inf.Name);
}
foreach (DirectoryInfo Dir in Directorys)//逐个获取文件夹名称,并递归调用方法本身
{
CopyDirectory(DirectoryPath + "\\" + Dir.Name, DirAddress + "\\" + s);
}
#endregion
}
以上是已经通过检验成功的代码,是通过递归的方式来逐个复制文件和创建文件夹.还一种方法是通过使用DOS命令行来实现的,可是不知道为什么同样的命令行,我在CMD中使用可以,在程序中就不行呢,请指教。
以下是代码:
#region
//方法一:DOS命令:xcopy c:\docume~1\andy e:\andy /s/e 未实现
string s = DirectoryPath.Substring(DirectoryName(DirectoryPath));//获取文件夹名
Directory.CreateDirectory(DirAddress + "\\" + s);//创建文件夹
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "xcopy \"" + DirectoryPath + "\" \"" + DirAddress + "\\" + s + "\" /s/e";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
#endregion