1

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);
Ken White
  • 123,280
  • 14
  • 225
  • 444
Jimmy K
  • 89
  • 1
  • 9
  • Look at [MSDN's How to: Copy Directories](http://msdn.microsoft.com/en-us/library/bb762914.aspx) –  May 13 '14 at 22:58
  • I have looked at this. I'm just very close here and was hoping that it was something simple...as it always seems to be. This is also 4.5 and I, unfortunately am working with 2008 – Jimmy K May 13 '14 at 23:02
  • Wait, you consider the code there in the MSDN How-To not as simple? And why do you think it is 4.5 specific? It's not... –  May 13 '14 at 23:06

1 Answers1

1

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));
}
Community
  • 1
  • 1
Noctis
  • 11,507
  • 3
  • 43
  • 82
  • Yup, I wish I would have stumbled upon your linked solution. Problem solved. Thanks Noctis! – Jimmy K May 13 '14 at 23:25
  • No worries, glad I could have been of assistance. I hope that what you'll take from this is **1.** search for your question before asking, and **2.** Files and Folders are different animals, and you need to know what you're dealing with :) – Noctis May 14 '14 at 00:12
  • I truly tried searching. Spent an hour looking, my apologies for the repetition. – Jimmy K May 14 '14 at 14:51