我正在尝试将文件和文件夹复制到另一个新文件夹。
我已经将文件复制到这个新文件夹了,但是如何复制目录呢。
这是我目前使用的代码。
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)
{
}
答案 0 :(得分: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));
}
}
答案 1 :(得分: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);
}
}
}