在:DFM文件与XML文件互转 中,用到的dfm文件必须为文本格式, 如果是二进制格式, 处理就会出错.
但是在处理中如何判断dfm是二进制文件, 而且再将二进制文件转为文本格式呢. ---
dfm文件二进制格式时, 其文件会加一个文件头, 其中前3个字节来标识其为二进制, 这三个字节分别为:$FF, $0A, $00. 因为这三个字节在文本类型的文件中是不可能存在的,所以可以判断这3个字节就可以了.
function IsBinDfm(const ADfmFileName: string): Boolean;
Var
mBinStream:TMemoryStream;
mBuff : array [0..2] of byte;
begin
mBinStream := TMemoryStream.Create;
try
mBinStream.LoadFromFile(ADfmFileName);
mBinStream.Read(mBuff, 3);
//前三字节: $FF, $0A, $00
if (mBuff[0] = $FF) and (mBuff[1] = $0A) and (mBuff[2]= $00) then
Result := True
else
Result := False;
finally
mBinStream.Free;
end;
end;
判断出来后, 再将二进制转为文本格式就容易了.Delphi提供了ObjectResourceToText函数.写法如下:
procedure DfmBin2Txt(ADfmFileName: string);
Var
inFileStream: TMemoryStream;
outFileStream: TFileStream;
begin
inFileStream := TMemoryStream.Create;
inFileStream.LoadFromFile(ADfmFileName);
try
outFileStream := TFileStream.Create(ADfmFileName, fmCreate);
try
try
inFileStream.Seek(0, soFromBeginning);
ObjectResourceToText(inFileStream, outFileStream);
except
Raise Exception.Create('This dfm is bin, error on trans bin to txt.');
end;
finally
outFileStream.Free;
end;
finally
inFileStream.Free;
end;
end;
至此,大功告成!