Code given by MagellanTX is correct. Make sure that the user under which you run your application has a right to change the registry.