Tuesday, July 20, 2010

Copy Files / Folders

In the previous posts we have seen, how to check whether files and directories already exist, how they can be moved and how to list the contents of a directory.
Copying files can also be done with one command:


The paths have to exist, for example an exception is thrown if the folder "testfolder" does not exist.
The 3rd parameter is and states, whether the targetfile is to be overwritten if it already exists (true means overwriting, the default value for this optional parameter is false).

Ironically, copying folders is much harder than moving them. Moving files is just a small intervention in the file system, just the path of the directory has to be set to the new location.
When copying a file or directory this element has to be duplicated and "registered" in the file system.
When copying folders, this leads to the problem that the complete folder hiearchy including subfolders has to be cloned - in C# there exists no actual function for it.
Therefore we will now write our own. It will work recursive, calling itself with all subdirectories and thus copying the folder structure. Then, all files are copied (using System.IO; required) :

        private void CopyDirectory(string sourceDirectory, string destDirectory)
            DirectoryInfo ds = new DirectoryInfo(sourceDirectory); // this class is needed to read the folder content

            // create target directory if not yet existent
            if (!Directory.Exists(destDirectory))

            // recursivly call CoypDirectory() with all subfolders to clone the directory structure
            foreach (DirectoryInfo d in ds.GetDirectories())
                CopyDirectory(d.FullName, destDirectory + "\\" + d.Name);

            // get all files with GetFiles(), which does not return a File object but a FileInfo object
           // but this provides similiar functions, MoveTo() and CopyTo() are available
            foreach (FileInfo f in ds.GetFiles())
                f.CopyTo(destDirectory + "\\" + f.Name, true);

A sample call could like as follows:

No comments:

Post a Comment