Parcourir la source

add SafeLoadFile & SafeSaveFile

KngStr il y a 2 ans
Parent
commit
5e9e9990a4
1 fichiers modifiés avec 37 ajouts et 0 suppressions
  1. 37 0
      Source/ksIOUtils.pas

+ 37 - 0
Source/ksIOUtils.pas

@@ -117,11 +117,48 @@ type
       FCMinFileNameLen = 12;
   end;
 
+/// <summary>
+/// load bak file if exist to avoid error file
+/// </summary>
+procedure SafeLoadFile(AFile: string; ACallback: TProc; ABakExt: string = '.bak');
+/// <summary>
+/// use bak file if exist to avoid error file
+/// </summary>
+procedure SafeSaveFile(AFile: string; ACallback: TProc; ABakExt: string = '.bak');
+
 implementation
 
 uses
   System.StrUtils;
 
+procedure SafeLoadFile(AFile: string; ACallback: TProc; ABakExt: string);
+var
+  LFile: string;
+begin
+  LFile := AFile + ABakExt;
+  if FileExists(LFile) then begin
+    if FileExists(AFile) then
+      DeleteFile(AFile);
+    RenameFile(LFile, AFile);
+  end;
+  if FileExists(AFile) then
+    ACallback;
+end;
+
+procedure SafeSaveFile(AFile: string; ACallback: TProc; ABakExt: string);
+var
+  LFile: string;
+begin
+  LFile := AFile + ABakExt;
+  if FileExists(LFile) then
+    DeleteFile(LFile);
+  if (not FileExists(AFile)) or (not RenameFile(AFile, LFile)) then
+    LFile := '';
+  ACallback;
+  if LFile <> '' then
+    DeleteFile(LFile);
+end;
+
 { TDirectoryEx }
 
 class procedure TDirectoryEx.CheckGetFilesParameters(Path: string;