Saturday, September 17, 2011

Copy Directory from one location to another

Use below code to copy directory to another location:

        // Copy directory structure recursively

        public static void copyDirectory(string Src,string Dst){
            String[] Files;

            if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar) 
                Dst+=Path.DirectorySeparatorChar;
            if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            Files=Directory.GetFileSystemEntries(Src);
            foreach(string Element in Files){
                // Sub directories

                if(Directory.Exists(Element)) 
                    copyDirectory(Element,Dst+Path.GetFileName(Element));
                // Files in directory

                else 
                    File.Copy(Element,Dst+Path.GetFileName(Element),true);
            }
        }
 
The function takes two absolute paths (source directory and destination directory)
as parameters and returns a boolean equal to true when the copy succeeds. 
Please note that this function automatically overwrites a destination file with 
the same name. Of course all subdirectories are also copied recursively.  

No comments:

Post a Comment