一旦我的程序安装在客户端机器上,我如何强制我的程序在Windows 7上以管理员身份运行?
当前回答
您需要修改嵌入到程序中的清单。这适用于Visual Studio 2008及更高版本:项目+添加新项目,选择“应用程序清单文件”。将<requestedExecutionLevel>元素更改为:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
用户在启动程序时得到UAC提示。明智地使用;他们的耐心很快就会耗尽。
其他回答
如果出于某种原因需要纯代码解决方案,这里有一个独立的类文件。只需在应用程序启动时调用“AdminRelauncher.RelaunchIfNotAdmin()”:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
public static class AdminRelauncher
{
public static void RelaunchIfNotAdmin()
{
if (!RunningAsAdmin())
{
Console.WriteLine("Running as admin required!");
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
proc.Verb = "runas";
try
{
Process.Start(proc);
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
Environment.Exit(0);
}
}
}
private static bool RunningAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
我实现了一些代码来手动完成:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
在Visual Studio 2010中右键单击项目名称。 点击“查看Windows设置”,这会生成并打开一个名为“app.manifest”的文件。 在此文件中,将“asInvoker”替换为“requireAdministrator”,如文件中的注释部分所述。
您可以在EXE文件中嵌入清单文件,这将使Windows(7或更高版本)始终以管理员身份运行程序。
您可以在步骤6:创建和嵌入应用程序清单(UAC) (MSDN)中找到更多详细信息。
在Visual Studio 2008上工作时,右键单击项目->添加新项,然后选择应用程序清单文件。
在清单文件中,你会发现标签requestedExecutionLevel,你可以将级别设置为三个值:
<requestExecutionLevel level=“asInvoker” uiAccess=“false” />
OR
< requestdexecutionlevel level="requireAdministrator" uiAccess="false" />
OR
<requestExecutionLevel level=“highestAvailable” uiAccess=“false” />
要将应用程序设置为以管理员身份运行,必须选择中间的一个。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本