当该文件已经存在时,cannot创建文件。
如何解决这个
Directory.Move
已经为您创建文件夹。您只需要调整以下内容:
if (!Directory.Exists(@"E:\Sunny\C#FolderCopy"))
{
Directory.Move(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\");
}
FileSystem.CopyDirectory
。它位于视觉基本名称空间中,但根本不关心:
using Microsoft.VisualBasic.FileIO;
if (!Directory.Exists(@"E:\Sunny\C#FolderCopy"))
{
FileSystem.CopyDirectory(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\");
}
或使用此方法(取自
MMSDN
):
DirectoryCopy(".", @".\temp", true);
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
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);
}
}
}
这效果很好。如果该文件夹在源路径中为空,则不会在目标路径中创建具有相同名称的空文件夹。