8

I'm currently using Microsoft.Win32.Registry functions to create, delete, set/get values, etc. Is there any way to 'export' a certain key that contains the application's settings to a .REG file?

DeCaf
  • 6,026
  • 1
  • 29
  • 51
Sean
  • 81
  • 1
  • 2

3 Answers3

4

You could p/pinvoke RegSaveKeyEx.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
1

I've found out that When trying to create a valid REG file you need to follow certain rules:

Your file MUST contain this as the first line:

"Windows Registry Editor Version 5.00"

  1. On the next line add the full key path between brackets

  2. add the corresponding Name/Value pairs, each on its own line. the format is:

    • "ValueName" = "Value" (SZ type)
    • "ValueName" = dword:00000000 (dword type - always 8 digits)

For BINARY, MULTI_SZ, EXPAND_SZ... I can't quite comment since I've not worked with them.

  1. repeat 2 and 3 as necessary to add more keys/subkeys

Note that I've only used this to export/modify string(SZ) values; here's a little helper that works great, for exporting a single value:

    private void ExportRegistryKey(string RegistryKeyPath, string ValueName, string Value, string ExportFileName = "ExportedRegValue.reg")
    {
        string regTemplate = @"Windows Registry Editor Version 5.00\r\n[{0}]\r\n""{1}""=""{2}""";
        string regFileContent = string.Format(regTemplate, RegistryKeyPath, ValueName, Value);
        File.WriteAllText(ExportFileName, regFileContent);
        return true;
    }

Should you need to export multiple values, you could change the function to take a dictionary, using the value name as a key and the actual values as values, then looping then while appending to the regFileContent variable.

Keith Hughitt
  • 4,860
  • 5
  • 49
  • 54
Kemuel Sanchez
  • 636
  • 7
  • 13
0

Another way could be to use powershell for this. You can run ps scripts from c# as well. Here is a example of a ps script which exports to a .reg file.

Martijn B
  • 4,065
  • 2
  • 29
  • 41