2006. április 16., vasárnap

How to embed binary data in an executable (2)


Problem/Question/Abstract:

Is is possible to somehow embed an external executable file in a Delphi program? Or maybe another type of file for that matter like a zip file for instance. I want the file to be extractable from my program later on so that I can use it on another system.

Answer:

Here is a simple little component where you can save a file in the form file. You can add compression/decompression/encryption or whatever you like, but this demonstrates a possible storage process for data. Quick and simple to use.

unit Unit2;

interface

uses
  Classes, Sysutils;

type
  TFileResourceComponent = class(TComponent)
  private
    FStream: TMemoryStream;
    FFileName: TFileName;
    procedure SetFileName(const Value: TFileName);
    procedure ReadData(Stream: TStream);
    procedure WriteData(Stream: TStream);
  public
    procedure DefineProperties(Filer: TFiler); override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property FileName: TFileName read FFileName write SetFileName;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('REDSYS', [TFileResourceComponent]);
end;

{ TFileResourceComponent }

constructor TFileResourceComponent.Create(AOwner: TComponent);
begin
  inherited;
  FStream := TMemoryStream.Create;
end;

procedure TFileResourceComponent.DefineProperties(Filer: TFiler);
begin
  inherited;
  Filer.DefineBinaryProperty('Data', ReadData, WriteData, True);
end;

destructor TFileResourceComponent.Destroy;
begin
  inherited;
  FStream.Free;
end;

procedure TFileResourceComponent.ReadData(Stream: TStream);
begin
  if not (csDesigning in ComponentState) then
    FStream.CopyFrom(Stream, Stream.Size);
end;

procedure TFileResourceComponent.SetFileName(const Value: TFileName);
begin
  FFileName := Value;
end;

procedure TFileResourceComponent.WriteData(Stream: TStream);
var
  FS:
  TMemoryStream;
begin
  if FileExists(FFileName) then
  begin
    FS := TMemoryStream.Create;
    try
      FS.LoadFromFile(FFileName);
      Stream.CopyFrom(FS, FS.Size);
    finally
      FS.Free;
    end;
  end;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése