我正在开发一个 ASP.NET 应用程序,我必须将任何文件夹及其内容移动到另一个文件夹。假设我有一个 Main 文件夹,该文件夹中有 3 个子文件夹。每个子文件夹中都有一个文件。我想将文件夹及其所有内容移动到另一个地方。为此,我使用了以下代码
if (!Directory.Exists(@"E:\Sunny\C#FolderCopy"))
{
Directory.CreateDirectory(@"E:\Sunny\C#FolderCopy");
Directory.Move(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\");
}
但是当控件到达移动功能时出现错误
Cannot create a file when that file already exists.
如何解决这个问题
最佳答案
Directory.Move
已为您创建文件夹。您只需调整以下内容:
if (!Directory.Exists(@"E:\Sunny\C#FolderCopy"))
{
Directory.Move(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\");
}
如果您想复制文件夹(如您的评论所示),您可以使用FileSystem.CopyDirectory
。它位于 Visual Basic 命名空间中,但根本不用担心:
using Microsoft.VisualBasic.FileIO;
if (!Directory.Exists(@"E:\Sunny\C#FolderCopy"))
{
FileSystem.CopyDirectory(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\");
}
或者使用此方法(取自 msdn ):
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);
}
}
}
关于c# - 将文件夹及其内容移动到其他文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45207334/