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

时间:2017-07-20 06:53:44

标签: c#

我正在开发一个asp.net应用程序,我必须将任何文件夹及其内容移动到另一个文件夹。假设我有一个Main文件夹,在该文件夹中有3个子文件夹。在每个子文件夹中都有一个文件。我想将文件夹及其所有内容移动到另一个地方。为此我使用了以下代码

colnames(binary) <- df$ID
as.matrix(apply(binary[indices,]==1,1,function(a) paste0(colnames(binary)[a], collapse = "")))

但是当控件达到移动功能时错误出现

  

当该文件已存在时无法创建文件。

如何解决这个问题

2 个答案:

答案 0 :(得分:2)

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);
        }
    }
}

答案 1 :(得分:2)

递归文件移动。 调用此方法即可。

public static void MoveDirectory(string source, string target)
{
    var sourcePath = source.TrimEnd('\\', ' ');
    var targetPath = target.TrimEnd('\\', ' ');
    var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
                         .GroupBy(s=> Path.GetDirectoryName(s));
    foreach (var folder in files)
    {
        var targetFolder = folder.Key.Replace(sourcePath, targetPath);
        Directory.CreateDirectory(targetFolder);
        foreach (var file in folder)
        {
            var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
            if (File.Exists(targetFile)) File.Delete(targetFile);
            File.Move(file, targetFile);
        }
    }
    Directory.Delete(source, true);
}