通过对象系列化保存配置信息

来源:互联网 发布:windows远程mac 编辑:程序博客网 时间:2024/05/22 15:40

一个很好用的配置类,通过对象系列化保存配置信息

在about.com上看到一个简单好用的配置类,通过它可以很方便的保存、读取程序的配置信息。

(来源:http://delphi.about.com/od/windowsshellapi/a/reader-writer.htm)

unit uSettings;

 

interface

 

uses Classes;

{$M+}

 

type

  TCustomSettings = class

  public

    procedure LoadFromStream(const Stream: TStream);

    procedure LoadFromFile(const FileName: string);

    procedure SaveToStream(const Stream: TStream);

    procedure SaveToFile(const FileName: string);

  end;

 

implementation

 

uses TypInfo, Sysutils;

 

{ TCustomSettings }

 

procedure TCustomSettings.LoadFromFile(const FileName: string);

var

  Stream: TStream;

begin

  Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);

  try

    LoadFromStream(Stream);

  finally

    Stream.Free;

  end;

end;

 

procedure TCustomSettings.LoadFromStream(const Stream: TStream);

var

  Reader: TReader;

  PropName, PropValue: string;

begin

  Reader := TReader.Create(Stream, $FFF);

  Stream.Position := 0;

  Reader.ReadListBegin;

 

  while not Reader.EndOfList do

  begin

    PropName := Reader.ReadString;

    PropValue := Reader.ReadString;

    SetPropValue(Self, PropName, PropValue);

  end;

 

  FreeAndNil(Reader);

end;

 

procedure TCustomSettings.SaveToFile(const FileName: string);

var

  Stream: TStream;

begin

  Stream := TFileStream.Create(FileName, fmCreate);

  try

    SaveToStream(Stream);

  finally

    Stream.Free;

  end;

end;

 

procedure TCustomSettings.SaveToStream(const Stream: TStream);

var

  PropName, PropValue: string;

  cnt: Integer;

  lPropInfo: PPropInfo;

  lPropCount: Integer;

  lPropList: PPropList;

  lPropType: PPTypeInfo;

  Writer: TWriter;

begin

  lPropCount := GetPropList(PTypeInfo(ClassInfo), lPropList);

  Writer := TWriter.Create(Stream, $FFF);

  Stream.Size := 0;

  Writer.WriteListBegin;

  for cnt := 0 to lPropCount - 1 do

  begin

    lPropInfo := lPropList^[cnt];

    lPropType := lPropInfo^.PropType;

    if lPropType^.Kind = tkMethod then

      Continue;

 

    PropName := lPropInfo.Name;

    PropValue := GetPropValue(Self, lPropInfo^.Name);

    Writer.WriteString(PropName);

    Writer.WriteString(PropValue);

  end;

 

  Writer.WriteListEnd;

  FreeMem(lPropList);

  FreeAndNil(Writer);

end;

 

initialization

 

finalization

 

end.

---------------------------------------------------------------------------------------------------

使用方法:

  Type

    TAppCfg=Class(TCustomSettings)

    private

       FUserName:String;

       FIntValue:Integer;

    published

      proeprty UserName:String Read FUserName Write FUSerName;

      property IntValue:Integer Read FIntValue Write FIntValue;

    end;

用法:

var AppCfg:TAppCfg;

 

程序启动时读取:

  AppCfg:=TAppCfg.Create;

  AppCfg.LoadFromFile(ExtractFilePath(ParamStr(0))+'app.cfg');

 

程序退出时保存:

  AppCfg.SaveToFile(ExtractFilePath(ParamStr(0))+'app.cfg'));

原创粉丝点击