如何使用c#将所有文件从一个文件夹复制到另一个文件夹

本文关键字:文件夹 一个 复制 另一个 何使用 文件 | 更新日期: 2023-09-27 17:53:13

using System.IO;
namespace ConsoleApplication3
{
    public class SimpleFileCopy
    {
        static void Main()
        {
            string sourcePath = @"C:'Source'";
            string targetPath = @"C:'Files'";
            if (Directory.Exists(sourcePath))
            {
                DirectoryInfo dirinfo = new DirectoryInfo(sourcePath);
                DirectoryInfo[] listofSubDir=dirinfo.GetDirectories();
                foreach (var item in listofSubDir)
                {
                    var childItem = item.FullName + "''" + "C1";
                    string[] files = System.IO.Directory.GetFiles(childItem);
                    foreach (var file in files)
                    {
                        Console.WriteLine(file);
                    }

                }
                Console.Read();
            }
        }
    }
}

如何使用c#将所有文件从一个文件夹复制到另一个文件夹

从MSDN复制,有以下解决方案。它递归地将目录从源复制到目标。

using System;
using System.IO;
class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".'temp", true);
    }
    private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        DirectoryInfo[] dirs = dir.GetDirectories();
        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }
        // If the destination directory doesn't exist, create it. 
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }
        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }
        // If copying subdirectories, copy them and their contents to new location. 
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}
相关文章: