Search code examples
delphiregistry

How to resolve "Failed to set data" error when writing a String value in the Windows Registry?


When trying to write a value in the windows registry I get a "Failed to set data for "Value1" " error. I tried running the program as a administrator, creating the key manually and setting the permisions of the key for "Everyone" to full acess. But the error persists

I have used the following code to write the value:

var
   Registry: TRegistry;
 begin
   Registry := TRegistry.Create(KEY_READ);
     Registry.RootKey := HKEY_LOCAL_MACHINE;

     // False because otherwise it would create a new key
     try
     if not Registry.OpenKey(KeyLocation, True) then RaiseLastOSError;
     Registry.WriteString('Value1', 'text123');
    finally
      Registry.Free;
     end;
end;

How do I resolve this issue?


Solution

  • You are trying to write registry to HKEY_LOCAL_MACHINE branch part of the registry. This is a system level part of the registry that requires elevated privileges to be accessible.

    Or in other words you will have to run your application as administrator or request privileges elevation using manifest file.

    EDIT: Also you are opening the registry with KEY_READ access level which is only used for reading the registry but not writing to the registry.

    You can read more about Access levels here