How do I force my .NET application to run as administrator?

一旦我的程序安装在客户机上,我如何强制我的程序在Windows 7上以管理员身份运行?


You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.


Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal ).


我实现了一些代码来手动完成它:

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;
}
链接地址: http://www.djcxy.com/p/17180.html

上一篇: 使用WCF适配器服务项目的SAP身份验证

下一篇: 如何强制我的.NET应用程序以管理员身份运行?