此代码没有复制目录中所有文件的麻烦。但是,它不维护文件夹结构,只复制文件。关于我需要改变什么以保持文件夹结构的任何想法?
string server = cbServer.SelectedItem.ToString();
string input = "\\\\" + server + "\\F\\Input";
string folderPath = txtPath.Text;
foreach (var file in System.IO.Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories))
File.Copy(file, System.IO.Path.Combine(input, Path.GetFileName(file)), true);
答案 0 :(得分:1)
您没有处理文件夹,只是递归地将文件复制到目标目录中。
你可以这样做,主要来自这里:What is the best way to copy a folder and all subfolders and files using c#
static void Main(string[] args)
{
string source = @"C:\Users\Yaron.Fainstein\Desktop\z1";
string target = @"C:\Users\Yaron.Fainstein\Desktop\z1-out";
CopyFolder(new DirectoryInfo(source), new DirectoryInfo(target));
/*foreach (var file in System.IO.Directory.GetFiles(source, "*", SearchOption.AllDirectories))
{
File.Copy(file, System.IO.Path.Combine(target, Path.GetFileName(file)), true);
}*/
}
public static void CopyFolder(DirectoryInfo source, DirectoryInfo target) {
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFolder(dir, target.CreateSubdirectory(dir.Name));
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}