/// <summary> /// Copy directory. /// </summary> public static void DirCopy(string srcDir, string destDir, DirCopyOptions opts) { // Get the subdirectories for the specified directory. DirectoryInfo dirInfo = new DirectoryInfo(srcDir); if (!dirInfo.Exists) { throw new DirectoryNotFoundException($"Directory [{srcDir}] does not exist"); } // Get the files in the directory and copy them to the new location. try { FileInfo[] files; if (opts.FileWildcard == null) { files = dirInfo.GetFiles(); } else { files = dirInfo.GetFiles(opts.FileWildcard); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } foreach (FileInfo f in files) { opts.Progress?.Report(f.FullName); string destPath = Path.Combine(destDir, f.Name); f.CopyTo(destPath, opts.Overwrite); } } catch (UnauthorizedAccessException) { } // Ignore UnauthorizedAccessException // If copying subdirectories, copy them and their contents to new location. if (opts.CopySubDirs) { DirectoryInfo[] dirs; try { dirs = dirInfo.GetDirectories(); } catch (UnauthorizedAccessException) { return; } // Ignore UnauthorizedAccessException foreach (DirectoryInfo d in dirs) { string tempPath = Path.Combine(destDir, d.Name); DirCopy(d.FullName, tempPath, opts); } } }
/// <summary> /// Copy directory. /// </summary> public static void DirCopy(string srcDir, string destDir, DirCopyOptions opts) { // Get the subdirectories for the specified directory. DirectoryInfo root = new DirectoryInfo(srcDir); if (!root.Exists) { throw new DirectoryNotFoundException($"Directory [{srcDir}] does not exist"); } Queue <(DirectoryInfo SrcDir, string DestDir)> q = new Queue <(DirectoryInfo, string)>(); q.Enqueue((root, destDir)); while (0 < q.Count) { (DirectoryInfo di, string subDestDir) = q.Dequeue(); try { FileInfo[] files; if (opts.FileWildcard == null) { files = di.GetFiles(); } else { files = di.GetFiles(opts.FileWildcard); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(subDestDir)) { Directory.CreateDirectory(subDestDir); } foreach (FileInfo f in files) { opts.Progress?.Report(f.FullName); string destPath = Path.Combine(subDestDir, f.Name); f.CopyTo(destPath, opts.Overwrite); } } catch (UnauthorizedAccessException) { /* Ignore UnauthorizedAccessException */ } // If copying subdirectories, copy them and their contents to new location. if (opts.CopySubDirs) { DirectoryInfo[] dirs; try { dirs = di.GetDirectories(); } catch (UnauthorizedAccessException) { // Ignore UnauthorizedAccessException continue; } foreach (DirectoryInfo d in dirs) { string newDestDir = Path.Combine(subDestDir, d.Name); q.Enqueue((d, newDestDir)); } } } }