LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C#默認(rèn)以管理員身份運行程序

admin
2018年9月8日 15:22 本文熱度 5436

一、通過配置文件實現(xiàn)以管理員身份運行程序

Vista 和 Windows 7 操作系統(tǒng)為了加強安全,增加了 UAC(用戶賬戶控制) 的機制,如果 UAC 被打開,用戶即使是以管理員權(quán)限登錄,其應(yīng)用程序默認(rèn)情況下也無法對系統(tǒng)目錄,系統(tǒng)注冊表等可能影響系統(tǒng)運行的設(shè)置進行寫操作。這個機制大大增強了系統(tǒng)的安全性,但對應(yīng)用程序開發(fā)者來說,我們不能強迫用戶去關(guān)閉UAC,但有時我們開發(fā)的應(yīng)用程序又需要以 Administrator 的方式運行,即 Win7 中 以 as administrator 方式運行,那么我們怎么來實現(xiàn)這樣的功能呢?

我們在 win7 下運行一些安裝程序時,會發(fā)現(xiàn)首先彈出一個對話框,讓用戶確認(rèn)是否同意允許這個程序改變你的計算機配置,但我們編寫的應(yīng)用程序默認(rèn)是不會彈出這個提示的,也無法以管理員權(quán)限運行。本文介紹了 C# 程序如何設(shè)置來提示用戶以管理員權(quán)限運行。

首先在項目中增加一個 Application Manifest File

默認(rèn)的配置如下:

<?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="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
            If you want to change the Windows User Account Control level replace the
            requestedExecutionLevel node with one of the following.
        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />
            If you want to utilize File and Registry Virtualization for backward
            compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</asmv1:assembly>

我們可以看到這個配置中有一個 requestedExecutionLevel 項,這個項用于配置當(dāng)前應(yīng)用請求的執(zhí)行權(quán)限級別。這個項有3個值可供選擇,如下表所示:

ValueDescriptionComment
asInvokerThe application runs with the same access token as the parent process.Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
highestAvailableThe application runs with the highest privileges the current user can obtain.Recommended for mixed-mode applications. Plan to refractor the application in a future release.
requireAdministratorThe application runs only for administrators and requires that the application be launched with the full access token of an administrator.Recommended for administrator only applications. Internal elevation points are not needed. The application is already running elevated.

asInvoker : 如果選這個,應(yīng)用程序就是以當(dāng)前的權(quán)限運行。

highestAvailable: 這個是以當(dāng)前用戶可以獲得的最高權(quán)限運行。

requireAdministrator: 這個是僅以系統(tǒng)管理員權(quán)限運行。

默認(rèn)情況下是 asInvoker。

highestAvailable 和 requireAdministrator 這兩個選項都可以提示用戶獲取系統(tǒng)管理員權(quán)限。那么這兩個選項的區(qū)別在哪里呢?

他們的區(qū)別在于,如果我們不是以管理員帳號登錄,那么如果應(yīng)用程序設(shè)置為 requireAdministrator ,那么應(yīng)用程序就直接運行失敗,無法啟動。而如果設(shè)置為 highestAvailable,則應(yīng)用程序可以運行成功,但是是以當(dāng)前帳號的權(quán)限運行而不是系統(tǒng)管理員權(quán)限運行。如果我們希望程序在非管理員帳號登錄時也可以運行(這種情況下應(yīng)該某些功能受限制) ,那么建議采用 highestAvailable 來配置。

關(guān)于requestedExecutionLevel 設(shè)置的權(quán)威文檔請參考下面鏈接:

Create and Embed an Application Manifest (UAC)

下面是修改后的配置文件:

<?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="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
            If you want to change the Windows User Account Control level replace the 
            requestedExecutionLevel node with one of the following.
        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />
            If you want to utilize File and Registry Virtualization for backward 
            compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</asmv1:assembly>
配置文件修改后,我們運行應(yīng)用程序,就會首先彈出這樣一個提示框,點 Yes 后,程序才可以繼續(xù)運行,并且獲得系統(tǒng)管理員的權(quán)限。

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

下面再來看看程序如何知道當(dāng)前運行在系統(tǒng)管理員權(quán)限還是非系統(tǒng)管理員權(quán)限:

        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

這段代碼可以用于判斷當(dāng)前程序是否運行在系統(tǒng)管理員權(quán)限下。如果配置為 asInvoker,在win7 下,這個函數(shù)會返回 false ,如果是 requireAdministrator  則返回 true。

二、通過編程以管理員身份運行程序

在讀寫注冊表“HKEY_LOCAL_MACHINE\SOFTWARE\”下的項時,明明注冊表中有,但程序OpenSubKey始終返回Null,考慮到可能是因為權(quán)限的原因,于是我以管理員身份運行了一次,結(jié)果測試成功!原來真的是權(quán)限的問題,于是就在程序里面加入了默認(rèn)以管理員身份運行的代碼。下面讓我們看看是怎么實現(xiàn)的吧!

程序默認(rèn)以管理員身份運行

static void Main(string[] Args)
{
    /**
     * 當(dāng)前用戶是管理員的時候,直接啟動應(yīng)用程序
     * 如果不是管理員,則使用啟動對象啟動程序,以確保使用管理員身份運行
     */
    //獲得當(dāng)前登錄的Windows用戶標(biāo)示
    System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
    //創(chuàng)建Windows用戶主題
    Application.EnableVisualStyles();

    System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
    //判斷當(dāng)前登錄用戶是否為管理員
    if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
    {
        //如果是管理員,則直接運行
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
    else
    {
        //創(chuàng)建啟動對象
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        //設(shè)置運行文件
        startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
        //設(shè)置啟動參數(shù)
        startInfo.Arguments = String.Join(" ", Args);
        //設(shè)置啟動動作,確保以管理員身份運行
        startInfo.Verb = "runas";
        //如果不是管理員,則啟動UAC
        System.Diagnostics.Process.Start(startInfo);
        //退出
        System.Windows.Forms.Application.Exit();
    }
}


該文章在 2018/9/8 15:26:27 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調(diào)度、堆場、車隊、財務(wù)費用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點,圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務(wù)都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
中文字幕高潮波多野结衣 | 一级风流片A级国产 | 亚洲成AV人在线观看网址 | 日本精品在线一区欧美 | 午夜日网站一线在线观看 | 亚洲日韩一中文字暮AV |