1

我正在尝试将文件和文件夹复制到另一个新文件夹。

我已经将文件复制到这个新文件夹,但我该如何复制目录。

这是我到目前为止使用的代码。

 DirectoryInfo di = Directory.CreateDirectory(path);

            if(Directory.Exists(mainShape))
            {
                string [] shapeFiles = Directory.GetFiles(mainShape);
                string[] shapeFolders = Directory.GetDirectories(mainShape);

                foreach (string file in shapeFiles)
                {
                    fileName = Path.GetFileName(file);
                    destFile = Path.Combine(path, fileName);
                    System.IO.File.Copy(file, destFile, true);
                }

                foreach (string folder in shapeFolders)
                {

                }
4

2 回答 2

0
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)
    {
        var ff = new DirectoryNotFoundException(sourceDirName);
        Console.Write(("Source directory does not exist or could not be found: "  + ff));
        return;
    }

    // If the destination directory doesn't exist, create it. 
    if (!Directory.Exists(destDirName))
    {
        Directory.CreateDirectory(destDirName);
    }
        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);
            }
        }
}
于 2013-11-15T15:24:53.953 回答
0
DirectoryInfo src = new DirectoryInfo(@"E:\Test\Dir1");
DirectoryInfo dest = new DirectoryInfo(@"C:\Dir2");
CopyDirectory(src, dest);


static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
    {
        if (!destination.Exists)
        {
            destination.Create();
        }

        // Copy all files.
        FileInfo[] files = source.GetFiles();
        foreach (FileInfo file in files)
        {
            file.CopyTo(Path.Combine(destination.FullName,
                file.Name));
        }

        // Process subdirectories.
        DirectoryInfo[] dirs = source.GetDirectories();
        foreach (DirectoryInfo dir in dirs)
        {
            // Get destination directory.
            string destinationDir = Path.Combine(destination.FullName, dir.Name);

            // Call CopyDirectory() recursively.
            CopyDirectory(dir, new DirectoryInfo(destinationDir));
        }
    }

http://forums.asp.net/t/1668027.aspx/1

于 2013-05-27T01:46:16.330 回答