1 Replies - 1848 Views - Last Post: 18 May 2012 - 05:32 AM

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1658
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Recursively copy files in C#

Posted 04 March 2008 - 10:03 PM

Description: Pass the method the original directory and the destination directory and it will copy all files to the new directory.This is a snippet to recursively copy all files from a given directory to a new directory
//Namespace Reference
using System.IO;

/// 
/// Method for copying all the filesin a given directory
/// 
/// Directory the files are in
/// Directory the files are being copied to
public bool RecursiveCopy(string origDir, string destDir)
{
    bool status = false;
    //get all the info about the original directory
    DirectoryInfo dirInfo = new DirectoryInfo(origDir);
    //retrieve all the _fileNames in the original directory
    FileInfo[] files = dirInfo.GetFiles(origDir);
    //always use a try...catch to deal 
    //with any exceptions that may occur
    try
    {
        //loop through all the file names and copy them
        foreach (string file in Directory.GetFiles(origDir))
        {
            FileInfo origFile = new FileInfo(file);
            FileInfo destFile = new FileInfo(file.Replace(origDir, destDir));
            //copy the file, use the OverWrite overload to overwrite
            //destination file if it exists
            System.IO.File.Copy(origFile.FullName, destFile.FullName, true);
            //TODO: If you dont want to remove the original
            //_fileNames comment this line out
            File.Delete(origFile.FullName);
            status = true;
        }
        MessageBox.Show("All files in " + origDir + " copied successfully!");
    }
    catch (Exception ex)
    {
        status = false;
        //handle any errors that may have occurred
        MessageBox.Show(ex.Message);
    }
    return status;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Recursively copy files in C#

#2 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1230
  • View blog
  • Posts: 1,754
  • Joined: 24-August 11

Re: Recursively copy files in C#

Posted 18 May 2012 - 05:32 AM

Why don't you use FileInfo[] files in the foreach loop? The "file in files" will already by a FileInfo() object so you won't have to create a new one.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1