CSharp examples for File IO:Directory
Recursively copies a directory from one path to another, while creating any parent directories if they don't already exist.
//**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// using System.IO;//from w w w .j a v a2s . c om public class Main{ /// <summary> /// Recursively copies a directory from one path to another, while creating any parent directories if they don't /// already exist. /// </summary> /// <param name="source">Path to the directory to copy.</param> /// <param name="destination">Path determining where the directory copy will be placed.</param> public static void Copy(string source, string destination) { DirectoryInfo dir = new DirectoryInfo(source); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + source); } if (!Directory.Exists(destination)) Directory.CreateDirectory(destination); FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destination, file.Name); file.CopyTo(temppath, false); } foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destination, subdir.Name); Copy(subdir.FullName, temppath); } } }