一旦我的程序安装在客户端机器上,我如何强制我的程序在Windows 7上以管理员身份运行?
当前回答
我实现了一些代码来手动完成:
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”,如文件中的注释部分所述。
另一种方法是仅在代码中检测进程是否以admin身份运行,就像@NG..然后再次打开应用程序并关闭当前应用程序。
当应用程序仅在某些条件下运行时需要管理权限时,例如将其自身作为服务安装时,我使用此代码。所以它不需要像其他答案一样一直以管理员身份运行。
注意,在下面的代码中,NeedsToRunAsAdmin是一个检测当前条件下是否需要管理权限的方法。如果返回false,代码将不会提升自身。这是这种方法相对于其他方法的主要优势。
尽管这段代码具有上述优点,但它确实需要作为一个新进程重新启动自己,这并不总是您想要的。
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
您可以在EXE文件中嵌入清单文件,这将使Windows(7或更高版本)始终以管理员身份运行程序。
您可以在步骤6:创建和嵌入应用程序清单(UAC) (MSDN)中找到更多详细信息。
这不会强制应用程序以管理员身份工作。 这是这个答案的简化版本,上面的@NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
您可以使用ClickOnce Security Settings创建清单,然后禁用它:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
单击后,将在项目的属性文件夹下创建一个名为app.manifest的文件,一旦创建,您可以取消选中启用ClickOnce安全设置选项
打开该文件并更改这一行:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
这将使程序需要管理员权限。
推荐文章
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应