use safe copy file on single file updating

This commit is contained in:
Pilzinsel64
2024-09-04 11:24:20 +02:00
parent 98d6d4d60a
commit 16a96329b5
2 changed files with 31 additions and 26 deletions

View File

@@ -10,31 +10,7 @@ public static class Utils
foreach (FileInfo sFile in sourceDir.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
{
var dFile = new FileInfo(Path.Combine(destinationDir.FullName, sFile.Name));
var triesLeft = 1;
while (triesLeft > 0)
{
triesLeft--;
try
{
sFile.CopyTo(dFile.FullName, true);
}
catch (IOException)
{
if (triesLeft == 0 && File.Exists(dFile.FullName))
{
var oldFile = dFile.FullName + ".old";
File.Delete(oldFile);
File.Move(dFile.FullName, oldFile, true);
File.Delete(oldFile);
triesLeft++;
}
}
catch (Exception)
{
}
}
CopyFile(sFile, dFile);
}
foreach (DirectoryInfo sDir in sourceDir.EnumerateDirectories("*", SearchOption.TopDirectoryOnly))
@@ -43,4 +19,33 @@ public static class Utils
CopyFiles(sDir, dDir);
}
}
public static void CopyFile(FileInfo sourceFile, FileInfo destinationFile)
{
var triesLeft = 1;
while (triesLeft > 0)
{
triesLeft--;
try
{
sourceFile.CopyTo(destinationFile.FullName, true);
}
catch (IOException)
{
if (triesLeft == 0 && File.Exists(destinationFile.FullName))
{
var oldFile = destinationFile.FullName + ".old";
File.Delete(oldFile);
File.Move(destinationFile.FullName, oldFile, true);
File.Delete(oldFile);
triesLeft++;
}
}
catch (Exception)
{
}
}
}
}