Tech Off Thread

13 posts

How? Copy directories in C#?

Back to Forum: Tech Off
  • User profile image
    Cybermagell​an

    With the amount of files/folders we want to move as users why does it seem like there isn't a Directory.Copy(source,dest) in C#?

    Anyone know probably the easiest way I can copy a folder (and sub directories) in C# across network shares?

  • User profile image
    W3bbo

    You'll have to do it recursivly with the FileInfo.CopyTo method.

    Fortunately it's not that hard....

    void CopyDirectory(String source, String destination) {

    // argument validation goes here, CBA to do it now

    DirectoryInfo dir = new DirectoryInfo(source);
    String[] files = dir.GetFiles("*");
    foreach(String filePath in files) {

    filePath.CopyTo( Path.Combine( destination, file.Name );

    }

    String[] children = dir.GetSubdirectories();
    foreach(String dirPath in children) {
    CopyDirectory( Path.Combine(source, dirPath), Path.Combine(destination, dirPath);
    }

    }


    Something like that....

  • User profile image
    Cybermagell​an

    Ya that's not quite doing it....

  • User profile image
    W3bbo

    Cybermagellan wrote:
    Ya that's not quite doing it....


    It's more like psuedocode than actually working, I think I got the SubDirectories list bit wrong.

    But what do you mean by "not quite doing it"?

  • User profile image
    Cannot​Resolve​Symbol
  • User profile image
    sgomez

    CannotResolveSymbol wrote:
    Google is your friend

    Tafiti is also your friend Wink

    Seba

  • User profile image
    Cybermagell​an

    It's wierd going from XML/HTML style coding back to OOP code....thanks I was able to get it to work.

  • User profile image
    Secret​Software

    using System;
    using System.IO;

    class CopyDir
    {
        public static void Copy(string sourceDirectory, string targetDirectory)
        {
            DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
            DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

            CopyAll(diSource, diTarget);
        }

        public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it's 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 each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }

        public static void Main()
        {
            string sourceDirectory = @"c:\sourceDirectory";
            string targetDirectory = @"c:\targetDirectory";

            Copy(sourceDirectory, targetDirectory);
        }

        
    }

  • User profile image
    littleguru

    My way. Slightly different from SecretSoftware's one:

    public static class CopyUtility
    {
        // Copies all files from one directory to another.
        public static void CopyAllFiles(string sourceDirectory, string targetDirectory, bool recursive)
        {
            if (sourceDirectory == null)
                throw new ArgumentNullException("sourceDirectory");
            if (targetDirectory == null)
                throw new ArgumentNullException("targetDirectory");

            // Call the recursive method.
            CopyAllFiles(new DirectoryInfo(sourceDirectory), new DirectoryInfo(targetDirectory), recursive);
        }

        // Copies all files from one directory to another.
        public static void CopyAllFiles(DirectoryInfo source, DirectoryInfo target, bool recursive)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (target == null)
                throw new ArgumentNullException("target");

            // If the source doesn't exist, we have to throw an exception.
            if (!source.Exists)
                throw new DirectoryNotFoundException("Source directory not found: " + source.FullName);
            // If the target doesn't exist, we create it.
            if (!target.Exists)
                target.Create();

            // Get all files and copy them over.
            foreach (FileInfo file in source.GetFiles())
            {
                file.CopyTo(Path.Combine(target.FullName, file.Name), true);
            }

            // Return if no recursive call is required.
            if (!recursive) return;

            // Do the same for all sub directories.
            foreach (DirectoryInfo directory in source.GetDirectories())
            {
                CopyAllFiles(directory, new DirectoryInfo(Path.Combine(target.FullName, directory.Name)),
                    recursive);
            }
        }
    }

  • User profile image
    littleguru

    But nothing goes over extension methods Cool

    public static class DirectoryInfoExtensions
    {
        // Copies all files from one directory to another.
        public static void CopyTo(this DirectoryInfo source, string destDirectory, bool recursive)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (destDirectory == null)
                throw new ArgumentNullException("destDirectory");

            // If the source doesn't exist, we have to throw an exception.
            if (!source.Exists)
                throw new DirectoryNotFoundException("Source directory not found: " + source.FullName);
            // Compile the target.
            DirectoryInfo target = new DirectoryInfo(destDirectory);
            // If the target doesn't exist, we create it.
            if (!target.Exists)
                target.Create();

            // Get all files and copy them over.
            foreach (FileInfo file in source.GetFiles())
            {
                file.CopyTo(Path.Combine(target.FullName, file.Name), true);
            }

            // Return if no recursive call is required.
            if (!recursive)
                return;

            // Do the same for all sub directories.
            foreach (DirectoryInfo directory in source.GetDirectories())
            {
                CopyTo(directory, Path.Combine(target.FullName, directory.Name), recursive);
            }
        }
    }


    and the usage looks like this:

    var source = new DirectoryInfo(@"C:\users\chris\desktop");
    source.CopyTo(@"C:\users\chris\desktop_backup", true);

  • User profile image
    keeron

    littleguru wrote:
    But nothing goes over extension methods



    This would be a good time to start a section / thread in the Sandbox area (or here as sticky) and put the various "C9" extensions in there. I've seen similar examples (utility methods on framework classes) on other forums and internally that could be turned into extensions and used in other areas.

    I hope somone does a codeplex project with some useful (Powerful) extensions like the entire Linq feature!

  • User profile image
    PerfectPhase

    Cybermagellan wrote:
    
    Anyone know probably the easiest way I can copy a folder (and sub directories) in C# across network shares?


    Instantiate powershell runtime and do the copy via that!

  • User profile image
    odujosh

    PerfectPhase wrote:
    
    Cybermagellan wrote:
    
    Anyone know probably the easiest way I can copy a folder (and sub directories) in C# across network shares?


    Instantiate powershell runtime and do the copy via that!


    While I enjoy your enthusiasm for powershell. The dependcy does not warrent what you get. (unless you already have that dependencie) 

    Recursive code is good for you.

    Having to deploy more dependencies is usually bad.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.