无法以管理员身份修改C#中的注册表(或运行管理级别的命令)
本文关键字:管理 运行 命令 注册表 身份 管理员 修改 | 更新日期: 2023-09-27 18:21:32
我正在创建一个将修改Windows服务的应用程序。但是,由于某些原因,它不允许我运行"cs config SERVICE_NAME set=SETTING"或修改注册表来更改服务的启动设置,因为需要Admin我已经在管理员帐户上授予它完全的管理员访问权限。
无论我做什么,它总是会出现一个错误,说它没有注册表的访问权限,或者因为没有权限而不会用CMD设置它。它被卡住的特定服务被称为"DCOM服务器进程启动器"
以下是我的应用程序清单中的安全设置
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet ID="Custom" SameSite="site" />
</applicationRequestMinimum>
</security>
</trustInfo>
这赋予它启动程序时的管理权限。我甚至手动右键单击了该文件并选择了"以管理员身份运行",但它仍然不起作用。
要进入注册表,这是代码,它还包含CMD进程。
RegistryKey key = null;
key = Registry.LocalMachine.OpenSubKey("SYSTEM''CurrentControlSet''Services''" + service, true); //true should make it Read/Write??
if (key != null)
{
//cmd.issueCmd("sc config " + service + " start= " + setting); //set a service with CMD
key.SetValue("Start", val, RegistryValueKind.DWord); //set a service with Registry
if (setting.Equals("delayed-auto"))
{
key.SetValue("DelayedAutoStart", 1, RegistryValueKind.DWord); //Add the Delayed-Start Registry if needed
}
}
if (key != null)
{
key.Close();
}
return;
这是CMD流程代码:
//Create a Hidden CMD Prompt to issue commands
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.FileName = "cmd.exe";
processStartInfo.Verb = "runas"; //should give it admin??
cmd = Process.Start(processStartInfo);
经过大量研究,我找到了解决方案。我使用了这篇关于代码项目的文章中提供的例子:http://www.codeproject.com/Articles/7665/Extend-ServiceController-class-to-change-the-Start
在设置并更改为我需要的方式后,所有Windows操作系统(至少XP和更新版本)的一切都很好。