move文件夹及其内容到其他文件夹 我正在处理ASP.NET应用程序,我必须将任何文件夹及其内容移至另一个文件夹。假设我有一个主文件夹,在该文件夹中有3个子文件夹。在每个子文件夹中都有一个

问题描述 投票:0回答:2
但是,当控件到达移动功能时,错误会出现AS

当该文件已经存在时,cannot创建文件。

如何解决这个

Directory.Move
已经为您创建文件夹。您只需要调整以下内容:

if (!Directory.Exists(@"E:\Sunny\C#FolderCopy")) { Directory.Move(@"E:\Sunny\C#Folder\", @"E:\Sunny\C#FolderCopy\"); }
c#
2个回答
4
投票
如果您想复制文件夹(如评论所示),则可以使用

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

移动文件移动。 调用此方法及其所有操作。 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); }

这效果很好。如果该文件夹在源路径中为空,则不会在目标路径中创建具有相同名称的空文件夹。
    

3
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.