Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting registry keys to a .REG file in C#

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?

like image 580
Sean Avatar asked Oct 15 '11 06:10

Sean


2 Answers

You could p/pinvoke RegSaveKeyEx.

like image 159
Alex K. Avatar answered Oct 23 '22 15:10

Alex K.


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.

like image 41
Kemuel Sanchez Avatar answered Oct 23 '22 13:10

Kemuel Sanchez