tags:

views:

1105

answers:

2

C# winforms - How can I import a reg file into the registry? The following code is displaying a confirmation box to the user (yes/no).

Process regeditProcess = Process.Start("key.reg", "/S /q"); // not working
regeditProcess.WaitForExit(); 
+4  A: 

Send the file as a parameter to regedit.exe:

Process regeditProcess = Process.Start("regedit.exe", "/s key.reg");
regeditProcess.WaitForExit();

Source: http://www.mycsharpcorner.com/Post.aspx?postID=29

Kobi
what I was looking for, thank you.
Power-Mosfet
One helpful hint, make sure the file name is enclosed with quotes if it contains spaces as it would on the command line.
doobop
A: 

Instead of executing a .reg file, you should be able to make your changes to the registry using the functionality provided in the Microsoft.Win32 namespace.

It is quite easy to create a registry key using this API:

RegistryKey key = Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name", "Isabella");
key.Close();

Unless you need to create a bulk load of new keys, I believe the API is a more scalable and maintable approach. If at some point, you need decide to make it optional to write your settings in the system-wide or the per-user branch of the registry, most of your code will be reusable for both cases. Simply pick another key to do the changes upon.

Maybe more important, the API lets you specify exactly (in code) how to handle cases where the key(s) you are inserting already exists in the registry. Should i delete the existing keys and insert mine, updates values within the existing keys, silently ignore or raise an exception?

Jørn Schou-Rode
Is there any particular reason he should be doing it using the API instead?
Lasse V. Karlsen
Assume the OP needs to install an official patch, which is a huge reg file. There are always valid reasons to do things.
Kobi
I can tell is a huge reg file. thats way setValue for each can be pain in the *ss.
Power-Mosfet
I agree with the three of you, that a `reg` is the right choice in some cases, and I have updated my answer with some arguments for why/when to use the API.
Jørn Schou-Rode