开发者

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?


You could p/pinvoke RegSaveKeyEx.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜