Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#42

AW: Ini-Inhalt geht in sehr seltenen Fällen verloren (TMemIniFile)

  Alt 12. Jan 2016, 00:13
Mein Vorschlag wäre:
Delphi-Quellcode:
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.
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat