Sco*_*owe 140 .net c# windows windows-services process-elevation
我正在尝试使用InstallUtil.exe安装服务但通过调用Process.Start.这是代码:
ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
System.Diagnostics.Process.Start (startInfo);
Run Code Online (Sandbox Code Playgroud)
其中m_strInstallUtil是完全限定的路径和exe"InstallUtil.exe",并且strExePath是我的服务的完全限定路径/名称.
从提升的命令提示符运行命令行语法有效; 从我的应用程序运行(使用上面的代码)没有.我假设我正在处理一些进程提升问题,那么我如何在高架状态下运行我的进程?我需要看一下ShellExecute吗?
这一切都在Windows Vista上.我正在VS2008调试器中运行升级到管理员权限的进程.
我也试过设置,startInfo.Verb = "runas";但似乎没有解决问题.
mdb*_*mdb 170
您可以通过将startInfo对象的Verb属性设置为'runas'来指示应使用提升的权限启动新进程,如下所示:
startInfo.Verb = "runas";
Run Code Online (Sandbox Code Playgroud)
这将导致Windows的行为就像使用"以管理员身份运行"菜单命令从资源管理器启动进程一样.
这确实意味着UAC提示将出现并且需要由用户确认:如果这是不合需要的(例如因为它将在漫长的过程中发生),您将需要运行整个主机进程通过创建和嵌入应用程序清单(UAC)来提升权限以要求"highestAvailable"执行级别:这将导致UAC提示在应用程序启动后立即显示,并导致所有子进程以提升的权限运行而无需其他提示.
编辑:我看到你刚编辑了你的问题,说"runas"不适合你.这真的很奇怪,因为它应该(在我的几个生产应用程序中也适用).但是,通过嵌入清单要求父进程以提升的权限运行应该绝对有效.
Cur*_*lop 45
此代码将上述所有内容放在一起,并使用admin privs重新启动当前的wpf应用程序:
if (IsAdministrator() == false)
{
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)
Run Code Online (Sandbox Code Playgroud)
更新:首选应用清单方式:
右键单击visual studio中的项目,添加新的应用程序清单文件,更改文件,以便您具有requireAdministrator设置,如上所示.
原始方式存在问题:如果将重启代码放在app.xaml.cs OnStartup中,即使调用Shutdown,它仍可能会短暂启动主窗口.如果没有运行app.xaml.cs init,我的主窗口会爆炸,在某些竞争条件下它会执行此操作.
小智 21
根据文章克里斯科里奥:使用Windows Vista用户帐户控制教你的应用程序,MSDN杂志,2007年1月,只ShellExecute检查嵌入式清单并在需要时提示用户提升,而CreateProcess其他API则不提示.希望能帮助到你.
另见:与.chm相同的文章.
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
Run Code Online (Sandbox Code Playgroud)
这将在没有UAC的情况下完成 - 无需启动新流程.如果正在运行的用户是我的案例的管理员组的成员.
我知道这是一篇很旧的帖子,但我只是想分享我的解决方案:
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo
{
UseShellExecute = true, //<- for elevation
Verb = "runas", //<- for elevation
WorkingDirectory = Environment.CurrentDirectory,
FileName = "EDHM_UI_Patcher.exe",
Arguments = @"\D -FF"
};
System.Diagnostics.Process p = System.Diagnostics.Process.Start(StartInfo);
Run Code Online (Sandbox Code Playgroud)
注意:如果 VisualStudio 已经运行 Elevated,则 UAC 对话框将不会显示,要测试它,请运行 bin 文件夹中的 exe。