Search code examples
stringdelphibinaryregistry

How to write String format of binary value to registry using Delphi and writebinary command?


Fore some good reason i need to write a string format of a binary value to a binary registry key, in other words I have a registry value like this :

 Windows Registry Editor Version 5.00

 [HKEY_LOCAL_MACHINE\SOFTWARE\Sonal]
 "Password"=hex:00,d6

I tried to write it to registry using following code :

procedure Tesct.Button2Click(Sender: TObject);
var
RegInfoExists : TRegistry;
EdStr : AnsiString;
begin

try
   RegInfoExists := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY);
   RegInfoExists.RootKey := HKEY_LOCAL_MACHINE;
   if RegInfoExists.OpenKey('SOFTWARE\Sonal',true) then
     EdStr := #$00#$d6;
     RegInfoExists.WriteBinaryData('Password', EdStr,
       Length(EdStr) * SizeOf(byte));

 except

 end;
 RegInfoExists.CloseKey;
 RegInfoExists.Free;
end;

And I got this :

 Windows Registry Editor Version 5.00

 [HKEY_LOCAL_MACHINE\SOFTWARE\Sonal]
 "Password"=hex:dc,d7

How i can do this ?


Solution

  • You are writing the value of the string variable which is the address of the string. That's because at an implementation level, strings are simply pointers.

    Instead you need to de-reference the pointer. Two commonly used ways to do that:

    RegInfoExists.WriteBinaryData('Password', EdStr[1], 
      Length(EdStr)*SizeOf(AnsiChar));
    

    or

    RegInfoExists.WriteBinaryData('Password', Pointer(EdStr)^, 
      Length(EdStr)*SizeOf(AnsiChar));
    

    If you really are just trying to write those two bytes then it is easier like this:

    const
      Password: array [0..1] of byte = ($00, $d6);
    ....
    RegInfoExists.WriteBinaryData('Password', Password, Length(Password));
    

    I would also comment that you should be very strict and precise in the way you look after resources. That means using try/finally correctly. Like this:

    SomeInstance := TSomeClass.Create;
    try
      .... do stuff with SomeInstance
    finally
      SomeInstance.Free;
    end;
    

    And you also seem to have omitted the begin/end that you need for the code that follows the if statement.