Quantcast
Channel: whileloop » code
Viewing all articles
Browse latest Browse all 10

copying or deleting everything in a directory (C#)

$
0
0

In C# we have the ability to move Directories or Files using System.IO.File.Move(sourceFile, destFile) and System.IO.Directory.Move(sourceDirPath, destDirPath) (making sure your paths use the string literal, ie var sourceDirPath = @"C:\Users\Public\public\test\"), however sadly there is no way to easily copy or delete entire directories (there is no Directory.Copy(fromDir, toDir) method available to us, only File.Copy(fromFile, toFile); and Directory.Delete(dir) only works for empty directories, so we need to empty them recursively!!). I have pulled together two methods to do this recursively.

The first is CopyAllDirectoriesAndFiles(string fromDirectory, string toDirectory), and also uses another method EnsureDirectoryExists(string dir):

private static void CopyAllDirectoriesAndFiles(string fromDirectory, string toDirectory) {
	if (Directory.Exists(fromDirectory)) {
		string[] files = Directory.GetFiles(fromDirectory);
		// make sure it exists
		EnsureDirectoryExists(toDirectory);
		// Copy the files and overwrite destination files if they already exist.
		foreach (string file in files) {
			var fileName = Path.GetFileName(file);
			var destFile = Path.Combine(toDirectory, fileName);
			File.Copy(file, destFile, true);
		}
		var di = new DirectoryInfo(fromDirectory);
		DirectoryInfo[] subDirs = di.GetDirectories();
		foreach (DirectoryInfo dirInfo in subDirs) {
			var directoryName = dirInfo.Name;
			var fromPath = Path.Combine(fromDirectory, directoryName);
			var toPath = Path.Combine(toDirectory, directoryName);
			EnsureDirectoryExists(toPath);
			// copy all files and folders across recursively
			CopyAllDirectoriesAndFiles(fromPath, toPath);
		}
	}
}

private static void EnsureDirectoryExists(string dir) {	
	if (!Directory.Exists(dir)) {
		Directory.CreateDirectory(dir);
	}
}

The second is DeleteAllDirectoriesAndFiles(string topDirectory):

private static void DeleteAllDirectoriesAndFiles(string topDirectory) {
	if (Directory.Exists(topDirectory)) {
		string[] files = Directory.GetFiles(topDirectory);
		foreach (string file in files) {
			File.Delete(file);
		}
		var di = new DirectoryInfo(topDirectory);
		DirectoryInfo[] subDirs = di.GetDirectories();
		foreach (DirectoryInfo dirInfo in subDirs) {
			var directoryName = dirInfo.Name;
			var fromPath = Path.Combine(topDirectory, directoryName);
			// delete all files and folders recursively
			DeleteAllDirectoriesAndFiles(fromPath);
		}
		// delete this folder
		Directory.Delete(topDirectory);
	}
}

Hopefully the inline comments are self-explanatory, if not, hit me up in the comments and I’ll provide you with more detail.



Viewing all articles
Browse latest Browse all 10

Trending Articles