我需要在 C# 中备份一个注册表项。我一直在尝试 P/Invoke RegSaveKey 无济于事。由于无法关闭组策略设置,我无法使用“Reg.exe”备份注册表。
这是所有代码:
private static UIntPtr GetKey(string registryPath)
{
UIntPtr hKey = UIntPtr.Zero;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, registryPath, 0, KEY_READ, out hKey) != 0)
{
throw new Exception("Error getting key!");
}
return hKey;
}
private static void ExportRegistry(string registryPath)
{
UIntPtr key = UIntPtr.Zero;
try
{
key = GetKey(registryPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
if (key == UIntPtr.Zero)
{
Console.WriteLine("Not key to export!");
return;
}
try
{
RegSaveKey(key, "c:\\temp\\test.reg", IntPtr.Zero);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
if (key != UIntPtr.Zero)
{
RegCloseKey(key);
}
}
private static int KEY_READ = 131097;
private static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int RegCloseKey(UIntPtr hKey);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int RegOpenKeyEx(UIntPtr hKey, string subKey, int ulOptions, int samDesired, out UIntPtr hkResult);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint RegSaveKey(UIntPtr hKey, string lpFile, IntPtr lpSecurityAttributes);