Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.