使用 .NET Core 3.1 和 C#,我試圖將一個目錄(包括所有子目錄和檔案)移動到另一個目錄。目標目錄可能包含與源目錄同名的檔案夾和檔案,例如“源/檔案夾/檔案.txt”可能已經存在于“目標/檔案夾/檔案.txt”中,但我想覆寫目標目錄中的所有內容。
我得到的錯誤是“System.IO.IOException:當該檔案已經存在時無法創建檔案。”,但是我在從源移動檔案之前洗掉了目標中已經存在的檔案(File.Delete before 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
當我通過 Windows 任務計劃程式運行應用程式時會發生此錯誤,我已將其設定為每天凌晨 3 點 30 分運行,我已指定該任務應“開始于”與 EXE 所在的檔案夾相同的檔案夾。
任何建議將不勝感激,謝謝!
uj5u.com熱心網友回復:
不要洗掉目標目錄中的現有檔案,而是嘗試使用File.Move(file, targetFile, overwrite: true).
順便說一下,有一個關于如何復制目錄的MSDN 示例。這不完全是您的用例,但無論如何可能會有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376370.html
標籤:C# 。网 asp.net核心 窗口任务调度程序 系统文件
上一篇:遞回復制一個字串
