Well when I started writing this function I had no Idea what to expect. I checked MSDN and I couldn’t find a function that can do this for me. I could be wrong because at midnight you can’t expect your brain to be working at peak 🙂
Alright so here is what I came up with. I will show you how you can use this function after defining the function
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
private static void CopyFolder(string SourceFolder, string targetPath, bool overwriteexistingFiles = true,string fileTypes ="*.*",bool createTargetIfNotexists = true) { bool ret = false; try { SourceFolder = SourceFolder.TrimEnd('\\', '/'); ; targetPath = targetPath.TrimEnd('\\','/'); // lets check if the source folder exists or not if (Directory.Exists(SourceFolder) == false) { Console.WriteLine("Source folder does not exist."); Environment.Exit(0); } else { // lets check if targetFolder exists or not, and then based on if createTargetIfNotexists is true or false if (createTargetIfNotexists && Directory.Exists(targetPath) == false) { Directory.CreateDirectory(targetPath); } else { throw new Exception("Target folder does not exist"); } string [] files = Directory.GetFiles(SourceFolder,fileTypes); foreach (string file in files) { FileInfo flinfo = new FileInfo(file); flinfo.CopyTo(targetPath + flinfo.Name, overwriteexistingFiles); } string [] dirs = Directory.GetDirectories(SourceFolder); foreach (string dir in dirs) { DirectoryInfo drinfo = new DirectoryInfo(dir); if (CopyDirectory(dir, targetPath + drinfo.Name, overwriteexistingFiles) == false) { throw new Exception("Unable to copy directory: "+dir); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } |
Lets see how we can use this function
[geshi lang=”csharp” nums=”1″ target=”_self” ]
1 |
CopyFolder(@"c:\myfolder", @"c:\copytofolder\"); |
You can pass optional param values as per requirement.
Above is an approach and you can off course always do better. If you would like to add something to this post please do so via leaving your comments.
I hope this helps
Cheers
i am getting CopyDirectory error saying name does not exit in current context