kmort
kmort

Reputation: 2928

C# writing to the registry

I am writing to an existing registry key with C# .NET 4.0 as Administrator on Windows 7 using the following code:

Microsoft.Win32.Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\MY\\SOFTWARE\\Name", "key_name", "key_value");

It appears to work just fine, but I've seen other folks on the web claim you need to do a Registry.Close() or it won't work.

Do I really need to OpenSubKey and Close the key if this already appears to work?

I'm not complaining that my code works, I just want to understand best practices.

Upvotes: 2

Views: 824

Answers (3)

Ehsan
Ehsan

Reputation: 32651

If you are using static methods of Registry class then you don't have to close explicitly as it will do that itself. From MSDN

In the .NET Framework version 2.0, the Registry class also contains static GetValue and SetValue methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they are used.

However, if this is not the case then calling the clise on registry will Closes the key and flushes it to disk if its contents have been modified. e.g.

RegistryKey rk = Registry.CurrentUser.CreateSubKey("RegistryOpenSubKeyExample");
rk.Close();

Upvotes: 2

user240141
user240141

Reputation:

Its a good practice to close the keys that are created. E.g.

//not actual code
Key1.Create()
Key 2 = Key1.SetValue();
and so on

So you need just reverse order to close the key. From child to parent

Upvotes: 0

Tallek
Tallek

Reputation: 1575

From MSDN: http://msdn.microsoft.com/en-us/library/5a5t63w8.aspx

The SetValue method opens a registry key, sets the value, and closes the key each time it is called. If you need to modify a large number of values, the RegistryKey.SetValue method might provide better performance. The RegistryKey class also provides methods that allow you to add an access control list (ACL) to a registry key, to test the data type of a value before retrieving it, and to delete keys.

Upvotes: 4

Related Questions