Having trouble copying files that are beyond the root level while maintaining folder structure [duplicate]

StackOverflow https://stackoverflow.com/questions/23642913

  •  22-07-2023
  •  | 
  •  

質問

This code has no troubles copying all files that are in the directory. But, it does not maintain folder structure it only copies the files. Any ideas on what I need to change in order to maintain folder structure?

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);
役に立ちましたか?

解決

You're not dealing with folders, you just recursively copying files into the target directory.

You can do this, mainly from here really : 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));
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top