C# WinForms - 我如何将一个reg
文件导入到注册表中?以下代码会向用户显示确认框(是/否)。
Process regeditProcess = Process.Start("key.reg", "/S /q"); // not working
regeditProcess.WaitForExit();
将文件作为参数发送到 regedit.exe
:
Process regeditProcess = Process.Start("regedit.exe", "/s key.reg");
regeditProcess.WaitForExit();
第二个回答中的代码是正确的,但不完整。当你引用的目录路径/文件路径中存在空格时,它将无法正常工作,例如C:\ProgramFiles\key.reg将正常工作,但C:\Program Files\key.reg不会正常工作,因为路径中有空格。
解决方案:
string directory= @"C:\Program Files (x86)\key.reg";
Process regeditProcess = Process.Start("regedit.exe", "/s \"" + directory + "\"");
regeditProcess.WaitForExit();
我尝试打开RegEdit,但每次都弹出确认提示(UAC已启用,没有提升权限)。建议使用"reg.exe"代替RegEdit(自Windows XP以来已包含在Windows中)。
Process proc = new Process();
try
{
proc.StartInfo.FileName = "reg.exe";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
string command = "import " + path;
proc.StartInfo.Arguments = command;
proc.Start();
proc.WaitForExit();
}
catch (System.Exception)
{
proc.Dispose();
}
不要执行.reg
文件,你应该使用Microsoft.Win32
命名空间提供的功能来更改注册表。
使用这个API创建注册表键非常容易:create a registry key.
RegistryKey key = Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name", "Isabella");
key.Close();
reg
是正确的选择,并且我已经更新了我的回答,并提供了一些为什么/何时使用API的论据。 - Jørn Schou-Rode