Tuesday, June 22, 2010

Copy Entire Folder from one location to another in .Net

Copying the entire file under the folder there is two ways
1. Using component
2. Using Programatically

=======================================================================================
1) Add this line of code and pass your source folder path and destination folder path, then this component will copying all the files from source to desc.

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);


2. Via Programatically

first you need to add namesapce System.IO on the top of the page


protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo SourceLoc = new DirectoryInfo(@"D:\Projects\SitePages\common");
DirectoryInfo TargetLoc = new DirectoryInfo(@"D:\Projects\Production\common");

CopyAllFiles(SourceLoc, TargetLoc);
}

///
/// Copy All files from the source directory into the target directory
///

///
///
public void CopyAllFiles(DirectoryInfo Source, DirectoryInfo target)
{
//Validate the existance of the target dir, if fail then create the dir
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}

//Copy individual file into the new directory
foreach (FileInfo file in Source.GetFiles())
{
file.CopyTo(Path.Combine(target.ToString(), file.Name), true);
}

//Recursion loop to copy each sub directory
foreach (DirectoryInfo diSource in Source.GetDirectories())
{
DirectoryInfo nexttarget = target.CreateSubdirectory(diSource.Name);
CopyAllFiles(diSource, nexttarget);
}
}

No comments:

Post a Comment