c# - 将文件夹及其内容移动到其他文件夹

标签 c#

我正在开发一个 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/

相关文章:

c# - 使用 Autofixture 生成副本

c# - Mock HttpClientFactory 使用 Moq Framework 创建模拟的 HttpClient

c# - 使用 WCF 的双向通信

c# - 在 C# 中将指向结构的指针作为函数参数传递

c# - MVC3- Razor : error while passing query string

c# - 将 DataGridTextColumn 的 IsReadOnly 绑定(bind)到 DataGridTemplateColumn 复选框 IsChecked

c# - 当我在 mvc 的 ModelState 中使用 Ajax 更新数据库时

c# - 调用方法时,什么时候引用类,什么时候引用对象?

c# - Json.NET 反序列化为带引用的动态对象

c# - WCF AJAX 无法推断架构。请求/响应主体被包装