程序启动时如何请求管理员权限?

我需要我的软件能够作为管理员运行在 WindowsVista (如果有人运行它没有管理员权限,它会崩溃)。

在启动其他软件时,我看到系统提示“此软件将以管理员身份运行”。你想继续吗?”当应用程序试图获得管理特权时。

在 WindowsVista 上运行 c # 应用程序时如何请求管理权限?

95340 次浏览

Add the following to your manifest file:

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

You can also use highestAvailable for the level.

Look here about embedding manifest files:

http://msdn.microsoft.com/en-us/library/bb756929.aspx

PS: If you don't have a manifest file, you can easily add a new one:

In Visual Studio, right click project -> Add Item -> Choose Application Manifest File ( under General for Visual C# items)

The added file will already have the above part, just change the level to requireAdministrator from asInvoker

Put this XML in a file called yourexename.exe.manifest:

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="highestAvailable" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>

For .Net (Visual Studio 2013), include a manifest file that request administrator elevation and using the compiler's /win32manifest flag, compose and provide a manifest file that requests this elevation. However, the following describe doing so within Visual Studio for a project name, App.Exe:

  1. Create a file with the following content (for convenience you may add the file to the Visual Studio project as a development resource by ensuring that it's Build Action is None and Copy to Output... is Do not copy. By convention manifest files are named after their output target, in this case App.Exe.manifest. If you require uiAccess (User Interface), the assembly must be strongly named.

    <?xml version="1.0" encoding="utf-8" ?>
    <asmv1:assembly manifestVersion="1.0"
    xmlns="urn:schemas-microsoft-com:asm.v1"
    xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
    xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <assemblyIdentity version="1.0.0.0" name="App" />
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    </requestedPrivileges>
    </security>
    </trustInfo>
    </asmv1:assembly>
    
  2. Edit the project dialogue's build panel Other flags: entry field to add the win32manifest flag and have Visual Studio invoke the compiler accordingly. For example, in this case,

    /win32manifest:App.Exe.manifest.

Note the following entry:

  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>