在 dotnet 程序,可以通過清單文件設置管理員權限啟動
通過下面代碼可以判斷當前的程序是管理員權限運行
var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { // 當前正在以管理員權限運行。 }
而設置軟件啟動權限是管理員權限可以添加清單文件,右擊添加 App.manifest 文件,此時要求在 csproj 設置 <ApplicationManifest>App.manifest</ApplicationManifest>
才可以
<PropertyGroup> <ApplicationManifest>App.manifest</ApplicationManifest> </PropertyGroup>
在 App.manifest 文件將 requestedPrivileges 替換下面代碼
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC 清單選項 如果想要更改 Windows 用戶帳戶控制級別,請使用 以下節點之一替換 requestedExecutionLevel 節點。n <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> 指定 requestedExecutionLevel 元素將禁用文件和注冊表虛擬化。 如果你的應用程序需要此虛擬化來實現向后兼容性,則刪除此 元素。 --> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo>
轉自:https://cloud.tencent.com/developer/article/1584709