» Help

How to convert Delphi forms from binary to text and vice versa

   

Here are some routines you can use to test and convert between Delphi's binary and text form (.dfm) file formats.

Test for a binary form file

// returns true if dfm file is in a binary format
function IsDFMBinary(FileName: string): Boolean;
var
  F: TFileStream;
  B: Byte;
begin
  B := 0;
  F := TFileStream.Create(FileName, fmOpenRead);
  try
    F.Read( B, 1 );
    Result := B = $FF;
  finally
    F.Free;
  end;
end;

Convert from binary to text and vice versa

// convert a binary dfm file to a text dfm file
function Dfm2Txt(Src, Dest: string): boolean;
var
  SrcS, DestS: TFileStream;
begin
  if Src = Dest then
  begin
    MessageDlg('Error converting dfm file to binary!. '
      + 'The source file and destination file names are the same.',
      mtError, [mbOK], 0);
    result := False;
    exit;
  end;
  SrcS := TFileStream.Create(Src, fmOpenRead);
  DestS := TFileStream.Create(Dest, fmCreate);
  try
    ObjectResourceToText(SrcS, DestS);
    if FileExists(Src) and FileExists(Dest) then
      Result := True
    else
      Result := False;
  finally
    SrcS.Free;
    DestS.Free;
  end;
end;

// convert a text DFM file to a binary DFM file
function Txt2DFM(Src, Dest: string): boolean;
var
  SrcS, DestS: TFileStream;
begin
  if Src = Dest then
  begin
    MessageDlg('Error converting dfm file to binary!. '
      + 'The source file and destination file names are the same.',
      mtError, [mbOK], 0);
    Result := False;
    exit;
  end;
  SrcS := TFileStream.Create(Src, fmOpenRead);
  DestS := TFileStream.Create(Dest, fmCreate);
  try
    ObjectTextToResource(SrcS, DestS);
    if FileExists(Src) and FileExists(Dest) then
      Result := True
    else
      Result := False;
  finally
    SrcS.Free;
    DestS.Free;
  end;
end;

Open a Binary DFM File as a Text Stream

/// open a binary DFM file as a text stream
function DfmFile2Stream(const Src: string; Dest: TStream): boolean;
var
  SrcS: TFileStream;
begin
  SrcS := TFileStream.Create(Src, fmOpenRead or fmShareDenyWrite);
  try
    ObjectResourceToText(SrcS, Dest);
    Result := True;
  finally
    SrcS.Free;
  end;
end;
Author: Bill Miller
Contributor: Bill Miller
Added: 2008-06-16
Last updated: 2008-06-16

« Return to contents »