unit System.IniFilesEx;
interface
uses
System.IniFiles,
System.SysUtils;
type
TSafeMemIniFile =
class( TMemIniFile )
private const
ExtOldData = '
.bak';
ExtOldEmpty = '
.ebak';
private
FSaveOnDestroy: Boolean;
procedure RestoreFileState(
const FileName:
string );
procedure DeleteFileIfExists(
const FileName:
string );
function GetOldFileName:
string;
function GetEmptyFileName:
string;
protected
property OldFileName :
string read GetOldFileName;
property EmptyFileName:
string read GetEmptyFileName;
public
constructor Create(
const FileName:
string );
overload;
constructor Create(
const FileName:
string;
const Encoding: TEncoding );
overload;
destructor Destroy;
override;
procedure UpdateFile;
override;
property SaveOnDestroy: Boolean
read FSaveOnDestroy
write FSaveOnDestroy
default true;
end;
implementation
uses
System.Classes,
System.IOUtils;
{ TSafeMemIniFile }
constructor TSafeMemIniFile.Create(
const FileName:
string );
begin
RestoreFileState( FileName );
inherited Create( FileName );
FSaveOnDestroy := true;
end;
constructor TSafeMemIniFile.Create(
const FileName:
string;
const Encoding: TEncoding );
begin
RestoreFileState( FileName );
inherited Create( FileName, Encoding );
FSaveOnDestroy := true;
end;
procedure TSafeMemIniFile.DeleteFileIfExists(
const FileName:
string );
begin
if TFile.Exists( FileName )
then
TFile.Delete( FileName );
end;
destructor TSafeMemIniFile.Destroy;
begin
if SaveOnDestroy
then
UpdateFile( );
inherited;
end;
function TSafeMemIniFile.GetEmptyFileName:
string;
begin
Result := FileName + ExtOldEmpty;
end;
function TSafeMemIniFile.GetOldFileName:
string;
begin
Result := FileName + ExtOldData;
end;
procedure TSafeMemIniFile.RestoreFileState(
const FileName:
string );
begin
if TFile.Exists( OldFileName )
or TFile.Exists( EmptyFileName )
then
begin
DeleteFileIfExists( FileName );
if TFile.Exists( OldFileName )
then
TFile.Move( OldFileName, FileName );
DeleteFileIfExists( EmptyFileName );
end;
end;
procedure TSafeMemIniFile.UpdateFile;
begin
RestoreFileState( FileName );
if TFile.Exists( FileName )
then
TFile.Move( FileName, OldFileName )
else
TFile.WriteAllText( EmptyFileName, '
' );
inherited;
DeleteFileIfExists( OldFileName );
DeleteFileIfExists( EmptyFileName );
end;
end.