1

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 ?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

in addition a begin ... end might be usefull.
Thank you for your time, Yes I forget to put begin .... end. No it is not just 2 byte. Yes I should be more careful about resources. tank you very much david

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.