I have developed this function but I'm not sure if this is the best (secure) way to write in resources without corrupt *.exe in case of fails.
What is the best way to write resources to a *.exe file?
procedure SaveToRes(const aResFileName, aResName: string; aMemoryStream : TMemoryStream);
var
myRes: THandle;
aUpdateResource : boolean;
begin
aUpdateResource := false;
if not(FileExists(aResFileName)) then
raise Exception.Create('File not found');
myRes := BeginUpdateResource(PChar(aResFileName),false);
if myRes = 0 then
raise Exception.Create('BeginUpdateResource');
try
aMemoryStream.Seek(0,0);
aUpdateResource := UpdateResource(myRes, RT_RCDATA, PChar(aResName), LANG_NEUTRAL, aMemoryStream.Memory, aMemoryStream.Size);
if not(aUpdateResource) then
RaiseLastOSError(GetLastError, '[UpdateResource]');
finally
if not(EndUpdateResource(myres, not(aUpdateResource))) then
RaiseLastOSError(GetLastError, '[EndUpdateResource]');
end;
end;
Usage:
var
aVal : LongInt;
aMemoryStream : TMemoryStream;
begin
aVal := 5;
aMemoryStream := TMemoryStream.create;
try
aMemoryStream.Write(aVal, sizeOf(aVal));
SaveToRes('C:\foo\bar.exe', 'myRes', aMemoryStream);
finally
aMemoryStream.free;
end;
end;