Directory-Copying Command Line Utility

Sat, 16 May 2009 14:27:53 -0400 - Author:
I created this command-line utility to help copy an unusual directory from one of my disks to another. It contained filenames with colons, making it useless to do so from Windows Explorer. This utility will also be useful for automated copying of directories in batch scripts and so on. The source code is below.
/*
 * (C) 2008 Peter O.
 * Permission is granted to anyone to copy, modify,
 * and redistribute this file.  Attribution to the
 * author would be appreciated but is not required.
 * No warranties are provided and all liabilities
 * are disclaimed.
 */

using System; using System.IO;

namespace copydir { class Program { public static void CopyFileOrDirectory(string src, string dest){ string destFile=Path.GetFileName(dest); if(destFile.Contains(":")) return; Console.WriteLine("{0} => {1}",src,dest); if(Directory.Exists(src) && !File.Exists(dest)){ Directory.CreateDirectory(dest); foreach(string s in Directory.GetFiles(src)){ string fileName=Path.GetFileName(s); string destFileName=Path.Combine(dest,fileName); CopyFileOrDirectory(s,destFileName); } foreach(string s in Directory.GetDirectories(src)){ string fileName=Path.GetFileName(s); string destFileName=Path.Combine(dest,fileName); CopyFileOrDirectory(s,destFileName); } } else if(File.Exists(src) && !Directory.Exists(dest)){ try { File.Delete(dest); File.Copy(src,dest); } catch(UnauthorizedAccessException e){ Console.Error.WriteLine(e.Message); } } } public static void Main(string[] args) { if(args.Length<2){ Console.WriteLine("Usage: copydir [sourcePath] [destinationPath]"); return; } CopyFileOrDirectory(args[0],args[1]); } } }
To use it, enter the name of the directory to copy and then enter the name of the directory to copy it to. For example, to copy "C:\Here Folder" to "C:\There", use this command line:
copydir "C:\Here Folder" C:\There
where "copydir" is the name of the directory-copying program.