-
Notifications
You must be signed in to change notification settings - Fork 5
/
inifilessafe.pas
70 lines (55 loc) · 1.37 KB
/
inifilessafe.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
unit inifilessafe;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles;
type TSafeIniFile = class(TIniFile)
truefilename, activefilename, tmpfilename: string;
constructor Create(const AFileName: string);
procedure UpdateFile; override;
destructor Destroy; override;
end;
implementation
uses bbutils, xquery.internals.lclexcerpt;
constructor TSafeIniFile.Create(const AFileName: string);
begin
truefilename := AFileName;
activefilename := AFileName + '.sav';
tmpfilename := AFileName + '~' + IntToStr(Random(10000)) + '.tmp';
CopyFile(truefilename, activefilename);
inherited Create(activefilename);
end;
procedure TSafeIniFile.UpdateFile;
const MAX_RETRIES = 5;
var
ok: Boolean;
retry: Integer;
begin
ok := false;
fileMoveReplace(activefilename, tmpfilename);
try
for retry := 1 to MAX_RETRIES do begin
try
inherited UpdateFile;
fileMoveReplace(activefilename, truefilename);
CopyFile(truefilename, activefilename); //this also retries
DeleteFile(tmpfilename);
ok := true;
exit;
except
on e: EFCreateError do begin
if retry >= MAX_RETRIES then raise;
sleep(30);
end;
end;
end;
finally
if not ok then
fileMoveReplace(tmpfilename, activefilename);
end;
end;
destructor TSafeIniFile.Destroy;
begin
inherited Destroy;
end;
end.