我可以复制多个目录中的所有文件,但我想要做的是将所有目录与其中的文件一起复制,因为它们是我复制的目录,而不是仅仅将文件放在目标文件夹中。这是我到目前为止的代码
{
string SelectedPath = (string)e.Argument;
string sourceDirName;
string destDirName;
bool copySubDirs;
DirectoryCopy(".", SelectedPath, true);
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
任何帮助将不胜感激
答案 0 :(得分:2)
没有用于复制目录的开箱即用方法。您可以做的最好是使用扩展方法。看看这个 - http://channel9.msdn.com/Forums/TechOff/257490-How-Copy-directories-in-C/07964d767cc94c3990bb9dfa008a52c8
以下是完整示例(刚刚测试过并且有效):
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var di = new DirectoryInfo("C:\\SomeFolder");
di.CopyTo("E:\\SomeFolder", true);
}
}
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);
}
}
}
}
答案 1 :(得分:1)
答案 2 :(得分:1)
也许在复制之前尝试查看路径是否存在。如果它不存在,那么创建它吗?
string folderPath = Path.GetDirectoryName(path);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
答案 3 :(得分:0)
这样做的聪明方法就像在nithins中一样。使用您的方法,您可以使用FileInfo.Directory信息来确定文件的来源,然后在需要时在目标中创建此目录。但是,nithins链接是一个更清洁的解决方案。