Wednesday, January 14, 2009

DirectoryInfo Move (UNC Compatible)

Ever wanted to move a whole directory, but .NET would not allow it? The only possible way was to create directory, at target, and copy each files to the new folder and delete the old one.

To make matter worse, you can't copy or move directory to a shared location, with a given UNC path.

The following code is an extension method to allow the built-in .NET DirectoryInfo class, to move an entire folder, even across servers.





///////////////////////////Directory Info Extension///////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace YourNameSpace
{
public static class DirectoryInfoExtension
{
///
/// Copy directory from one location to another, recursively.
///
///
///
///
///
public static DirectoryInfo CopyTo(this DirectoryInfo Source, DirectoryInfo Target, bool Overwrite)
{
string TargetFullPath = Target.FullName;

if (Overwrite && Target.Exists)
{
Target.Delete(true);

}
else if (!Overwrite && Target.Exists)
{
Target.MoveTo(Target.Parent.FullName + "\\" + Target.Name + "." + Guid.NewGuid().ToString());
}

//Restores target back, such that it's not pointing to the renamed, obsolete directory.
Target = new DirectoryInfo(TargetFullPath);

Target.Create();

CopyRecurse(Source, Target);

return Target;
}
///
/// Copy source recursively to target.
/// NOTE: This will create target subdirectories, but NOT target itself.
///
///
///
private static void CopyRecurse(DirectoryInfo Source, DirectoryInfo Target)
{
foreach (DirectoryInfo ChildSource in Source.GetDirectories())
{
DirectoryInfo ChildTarget = Target.CreateSubdirectory(ChildSource.Name);
CopyRecurse(ChildSource, ChildTarget);
}
foreach (FileInfo File in Source.GetFiles())
{
File.CopyTo(Target.FullName + "
\\" + File.Name);
}
}

///
/// This extension allows directory to be moved accross servers.
///
///
///
///
///
public static DirectoryInfo MoveTo(this DirectoryInfo Source, DirectoryInfo Target, bool Overwrite)
{
Source.CopyTo(Target, Overwrite);
Source.Delete(true);
return Target;
}
}
}

No comments:

Post a Comment