Copy Folders in C# using System.IO

后端 未结 9 825
傲寒
傲寒 2020-12-10 03:20

I need to Copy folder C:\\FromFolder to C:\\ToFolder

Below is code that will CUT my FromFolder and then will create my ToFolder. So my FromFolder will be gone and al

相关标签:
9条回答
  • 2020-12-10 04:08

    yes you are right.

    http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx

    has provided copy function .. or you can use another function

    http://msdn.microsoft.com/en-us/library/ms127960.aspx

    0 讨论(0)
  • 2020-12-10 04:08

    A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist

    class Utils
    {
        internal static void copy_dir(string source, string dest)
        {
            if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
            Directory.CreateDirectory(dest);
            foreach (string fn in Directory.GetFiles(source))
            {
                File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
            }
            foreach (string dir_fn in Directory.GetDirectories(source))
            {
                copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-10 04:13

    This link provides a nice example.

    http://msdn.microsoft.com/en-us/library/cc148994.aspx

    Here is a snippet

    // To copy all the files in one directory to another directory.
    // Get the files in the source folder. (To recursively iterate through
    // all subfolders under the current directory, see
    // "How to: Iterate Through a Directory Tree.")
    // Note: Check for target path was performed previously
    //       in this code example.
    if (System.IO.Directory.Exists(sourcePath))
    {
      string[] files = System.IO.Directory.GetFiles(sourcePath);
    
      // Copy the files and overwrite destination files if they already exist.
      foreach (string s in files)
      {
        // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
        destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
      }
    }
    
    0 讨论(0)
提交回复
热议问题