Move and copy Directory
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Td.Additional.IO
{
/// <summary>
/// Directory facilities.
/// </summary>
public static class Directory
{
/// <summary>
/// Moves the directory.
/// </summary>
/// <param name="sourceDirectory">The source directory.</param>
/// <param name="destinationDirectory">The destination directory.</param>
/// <param name="deleteSource">if set to <c>true</c> [delete source].</param>
public static void MoveDirectory(
string sourceDirectory,
string destinationDirectory,
bool deleteSource)
{
if (System.IO.Directory.Exists(sourceDirectory))
{
if (System.IO.Directory.GetDirectoryRoot(sourceDirectory) ==
System.IO.Directory.GetDirectoryRoot(destinationDirectory))
{
System.IO.Directory.Move(sourceDirectory, destinationDirectory);
}
else
{
try
{
CopyDirectory(new DirectoryInfo(sourceDirectory),
new DirectoryInfo(destinationDirectory));
if (deleteSource)
System.IO.Directory.Delete(sourceDirectory, true);
}
catch (Exception subEx)
{
throw subEx;
}
}
}
}
/// <summary>
/// Copies the directory.
/// </summary>
/// <param name="sourceDirectory">The source directory.</param>
/// <param name="destinationDirectory">The destination directory.</param>
public static void CopyDirectory(
DirectoryInfo sourceDirectory,
DirectoryInfo destinationDirectory)
{
if (!destinationDirectory.Exists)
destinationDirectory.Create();
FileInfo[] fiSrcFiles = sourceDirectory.GetFiles();
foreach (FileInfo fiSrcFile in fiSrcFiles)
fiSrcFile.CopyTo(Path.Combine(destinationDirectory.FullName, fiSrcFile.Name));
DirectoryInfo[] diSrcDirectories = sourceDirectory.GetDirectories();
foreach (DirectoryInfo diSrcDirectory in diSrcDirectories)
CopyDirectory(
diSrcDirectory,
new DirectoryInfo(
Path.Combine(destinationDirectory.FullName, diSrcDirectory.Name)));
}
}
}
Related examples in the same category