使用.NET Core3.1和C#,我试图将一个目录(包括所有子目录和文件)移到另一个目录。目标目录可能包含与源目录同名的文件夹和文件,例如,“source /文件夹/file.txt”可能已经存在于“目的地/文件夹/file.txt”中,但我想覆盖目标目录中的所有内容。
我得到的错误是"System.IO.IOException:当该文件已经存在时不能创建一个文件“。但是,在从源移出该文件之前,我正在删除目标中已经存在的文件(File.Delete先于File.Move),因此我不明白为什么会出现此错误。另外,由于某些原因,我无法100%地复制此错误。
这是我用来移动目录的代码(第137-155行):
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);
}这是我的错误的堆栈跟踪:
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException: Cannot create a file when that file already exists.
at System.IO.FileSystem.MoveFile(String sourceFullPath, String destFullPath, Boolean overwrite)
at Module_Installer.Classes.Bitbucket.MoveDirectory(String source, String target) in F:\git\module-installer\module-installer\Module Installer\Classes\Bitbucket.cs:line 147
at Module_Installer.Classes.Bitbucket.DownloadModuleFiles(Module module, String username, String password, String workspace, String repository, String commitHash, String versionNumber, String downloadDirectory, String installDirectory) in F:\git\module-installer\module-installer\Module Installer\Classes\Bitbucket.cs:line 113
at Module_Installer.Classes.OvernightInstall.ProcessInstalledModule(TenantModule tenantModule, Boolean skipBackup) in F:\git\module-installer\module-installer\Module Installer\Classes\OvernightInstall.cs:line 393
at Module_Installer.Classes.OvernightInstall.Run(Boolean skipBackup) in F:\git\module-installer\module-installer\Module Installer\Classes\OvernightInstall.cs:line 75
at Module_Installer.Program.Main(String[] args) in F:\git\module-installer\module-installer\Module Installer\Program.cs:line 40当我通过运行应用程序时会发生此错误,我已将其设置为每天凌晨03:30运行,我已经指定任务应该“在”EXE所在的文件夹中“启动”。
任何建议都将不胜感激,谢谢!
发布于 2021-12-08 09:43:55
不要删除目标目录中的现有文件,而是使用File.Move(file, targetFile, overwrite: true)覆盖它们。
顺便说一下,还有一个关于如何复制目录的MSDN示例。这并不完全是您的用例,但无论如何可能会有所帮助。
https://stackoverflow.com/questions/70272659
复制相似问题