Pages

Showing posts with label move. Show all posts
Showing posts with label move. Show all posts

Thursday, March 31, 2011

Copy all files from one Folder to Another Folder

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);
}
}
}
————————————————
Moving files from one  folder to another folder
DirectoryInfo dir1= new DirectoryInfo("F:Folder1");
          DirectoryInfo dir2 = new DirectoryInfo("F:Folder2");

          FileInfo[] Folder1Files = dir1.GetFiles();
          if(Folder1Files.Length > 0)
          {
               foreach(FileInfo aFile in Folder1Files)
               {
                   if(File.Exists("F:Folder2" + aFile.Name))
                   {
                      File.Delete("F:Folder2" + aFile.Name);
                   }
                  aFile.MoveTo("F:Folder2" + aFile.Name);
               }
          }