Friday 11 January 2013

Copy All files from One Folder to Another Dynamically

Copy All files from One Folder to Another Dynamically


Use the following Code-Snippet to Copy all files from One Folder to Another:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

public partial class Sample : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

DirectoryInfo sourcedinfo = new DirectoryInfo(@”E:\Copy);

DirectoryInfo destinfo = new DirectoryInfo(@”E:\Paste);

CopyAll(sourcedinfo, destinfo);

Console.Read();

}

public void CopyAll(DirectoryInfo source, DirectoryInfo target)

{

try

{

//check if the target directory exists

if (Directory.Exists(target.FullName) == false)

{

Directory.CreateDirectory(target.FullName);

}

//copy all the files into the new directory

foreach (FileInfo fi in source.GetFiles())

{

Console.WriteLine(@”Copying {0}\{1}, target.FullName, fi.Name);

fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);

}

//copy all the sub directories using recursion

foreach (DirectoryInfo diSourceDir in source.GetDirectories())

{

DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);

CopyAll(diSourceDir, nextTargetDir);

}

Console.WriteLine(Success);

}

catch (IOException ie)

{

Console.WriteLine(ie.Message);

}

}

}

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top