1. 程式人生 > >C#預設以管理員身份執行程式

C#預設以管理員身份執行程式

Vista 和 Windows 7 作業系統為了加強安全,增加了 UAC(使用者賬戶控制) 的機制,如果 UAC 被開啟,使用者即使是以管理員許可權登入,其應用程式預設情況下也無法對系統目錄,系統登錄檔等可能影響系統執行的設定進行寫操作。這個機制大大增強了系統的安全性,但對應用程式開發者來說,我們不能強迫使用者去關閉UAC,但有時我們開發的應用程式又需要以 Administrator 的方式執行,即 Win7 中 以 as administrator 方式執行,那麼我們怎麼來實現這樣的功能呢?

我們在 win7 下執行一些安裝程式時,會發現首先彈出一個對話方塊,讓使用者確認是否同意允許這個程式改變你的計算機配置,但我們編寫的應用程式預設是不會彈出這個提示的,也無法以管理員許可權執行。本文介紹了 C# 程式如何設定來提示使用者以管理員許可權執行。

首先在專案中增加一個 Application Manifest File

預設的配置如下:

<?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 項,這個項用於配置當前應用請求的執行許可權級別。這個項有3個值可供選擇,如下表所示:

Value Description Comment
asInvoker The 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.
highestAvailable The 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.
requireAdministrator The 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 : 如果選這個,應用程式就是以當前的許可權執行。

highestAvailable: 這個是以當前使用者可以獲得的最高許可權執行。

requireAdministrator: 這個是僅以系統管理員許可權執行。

預設情況下是 asInvoker。

highestAvailable 和 requireAdministrator 這兩個選項都可以提示使用者獲取系統管理員許可權。那麼這兩個選項的區別在哪裡呢?

他們的區別在於,如果我們不是以管理員帳號登入,那麼如果應用程式設定為 requireAdministrator ,那麼應用程式就直接執行失敗,無法啟動。而如果設定為 highestAvailable,則應用程式可以執行成功,但是是以當前帳號的許可權執行而不是系統管理員許可權執行。如果我們希望程式在非管理員帳號登入時也可以執行(這種情況下應該某些功能受限制) ,那麼建議採用 highestAvailable 來配置。

關於requestedExecutionLevel 設定的權威文件請參考下面連結:

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>
配置檔案修改後,我們執行應用程式,就會首先彈出這樣一個提示框,點 Yes 後,程式才可以繼續執行,並且獲得系統管理員的許可權。
.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; }

下面再來看看程式如何知道當前執行在系統管理員許可權還是非系統管理員許可權:

        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; }

這段程式碼可以用於判斷當前程式是否執行在系統管理員許可權下。如果配置為 asInvoker,在win7 下,這個函式會返回 false ,如果是 requireAdministrator  則返回 true。

二、通過程式設計以管理員身份執行程式

在讀寫登錄檔“HKEY_LOCAL_MACHINE\SOFTWARE\”下的項時,明明登錄檔中有,但程式OpenSubKey始終返回Null,考慮到可能是因為許可權的原因,於是我以管理員身份運行了一次,結果測試成功!原來真的是許可權的問題,於是就在程式裡面加入了預設以管理員身份執行的程式碼。下面讓我們看看是怎麼實現的吧!

程式預設以管理員身份執行

  1. staticvoid Main(string[] Args)  
  2.         {  
  3.             /** 
  4.              * 當前使用者是管理員的時候,直接啟動應用程式 
  5.              * 如果不是管理員,則使用啟動物件啟動程式,以確保使用管理員身份執行 
  6.              */
  7.             //獲得當前登入的Windows使用者標示
  8.             System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();  
  9.             //建立Windows使用者主題
  10.             Application.EnableVisualStyles();  
  11.             System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);  
  12.             //判斷當前登入使用者是否為管理員
  13.             if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))  
  14.             {  
  15.                 //如果是管理員,則直接執行
  16.                 Application.EnableVisualStyles();  
  17.                 Application.Run(new Form1());  
  18.             }  
  19.             else
  20.             {  
  21.                 //建立啟動物件
  22.                 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();  
  23.                 //設定執行檔案
  24.                 startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;  
  25.                 //設定啟動引數
  26.                 startInfo.Arguments = String.Join(" ", Args);  
  27.                 //設定啟動動作,確保以管理員身份執行
  28.                 startInfo.Verb = "runas";  
  29.                 //如果不是管理員,則啟動UAC
  30.                 System.Diagnostics.Process.Start(startInfo);  
  31.                 //退出
  32.                 System.Windows.Forms.Application.Exit();  
  33.             }  
  34.         }   

開啟程式集裡的Program.cs檔案,並將其中Main方法中的程式碼替換為以上程式碼即可實現程式預設以管理員身份執行。

相關推薦

C#預設管理員身份執行程式

Vista 和 Windows 7 作業系統為了加強安全,增加了 UAC(使用者賬戶控制) 的機制,如果 UAC 被開啟,使用者即使是以管理員許可權登入,其應用程式預設情況下也無法對系統目錄,系統登錄檔等可能影響系統執行的設定進行寫操作。這個機制大大增強了系統的安全性,但對應用程式開發者來說,我們不能強迫

C#如何管理員身份執行程式

  在使用winform程式獲取呼叫cmd命令提示符時,如果是win7以上的作業系統,會需要必須以管理員身份執行才會執行成功,否則無效果或提示錯誤。      比如在通過winform程式執行cmd命令時,某些情況下如果不是以管理員身份執行,則會提示命令無效。    

c# 設定管理員身份執行開發的軟體 visual studio 2017

用C#開發的軟體需要獲得管理員許可權對C盤檔案進行更改。此文更改C#的manifest檔案以達到雙擊執行開發出的軟體時提示以管理員身份執行的效果。 1.建立manifest檔案。 右擊專案-> 可在此更改檔名(字尾不能更改)-> 2.開啟新建立的manifes

win7 批處理檔案預設管理員身份執行及清除IE快取指令碼

1、指令碼預設以管理員身份執行 在win7中,批處理檔案有時需要以管理員身份執行,如清除 IE 快取的指令碼,若不使用管理員許可權,常常會卡死。 批處理檔案以管理員身份執行很簡單,可惜,竟然很長時間不知道怎麼去設定,原來總是在“相容性”裡設定以管理員身份執行,可是批處理檔案

在VS中如何讓C#語言編寫的程式自動管理員身份執行

 在Vista或Win7或Win8或Win10系統上exe程式預設不是以管理員身份執行的,它會被UAC(使用者帳戶控制)阻止訪問系統某些功能,如修改登錄檔操作、操作硬碟上的檔案等。但是有時我們確實需要程式在開始執行時就是以管理員身份執行的,這時我們在VS中需進行以下操作:

C# WinForm判斷Win7下程式是否管理員身份執行

如果程式不是以管理員身份執行,操作本地檔案會提示:System.UnauthorizedAccessException異常 Vista 和 Windows 7 作業系統為了加強安全,增加了 UAC(使用者賬戶控制) 的機制,如果 UAC 被開啟,使用者即使是以管理員許可權登

判斷程式是否是 管理員 身份執行 visual c++

// 判斷本程式是否是以管理員身份執行的 //BY :暗影行者 // date: 20110716 BOOL ExeIsAdmin() { #define ACCESS_READ 1 #define ACCESS_WRITE 2 // if(g_bIsN

C# WinForm判斷程式是否管理員身份執行,UAC許可權的提權與降權

另外新增2個相關文章(只有提權,沒有提到降低許可權): 歡迎轉載,但最好請註明  Jero 翻譯。 已提權、已經提升許可權的程序——可以理解為使用管理員許可權執行的。未提權、沒有提升許可權的程序——可以理解為使用 非 管理員許可權(既普通使用者許可權)執行的。 UAC機制是由Vista引出,並

Win7 C# 控制檯程式寫登錄檔被拒,需要管理員身份執行

      最近寫了一個控制檯程式,將程式的相關資訊註冊到登錄檔中。但是執行的時候提示寫登錄檔被拒。電腦的當前使用者沒有管理員的許可權。         如何給控制檯程式賦管理員的許可權呢?    

Win10下Visual Studio 2015編譯報“無法註冊程式集***dll- 拒絕訪問。請確保您正在管理員身份執行應用程式。對登錄檔項”***“的訪問被拒絕。”問題解決

原來在Win7下Visual Studio2008跑的好好的程式,現在在Win10下編譯報“無法註冊程式集dll- 拒絕訪問。請確保您正在以管理員身份執行應用程式。對登錄檔項”“的訪問被拒絕。”的錯誤。報錯資訊明面上看是讓你用管理員身份執行Visual Studio,然後開啟工程編譯就好了。

[技巧.Dotnet]輕鬆實現“強制.net程式管理員身份執行”。

使用場景: 程式中不少操作都需要特殊許可權,有時為了方便,直接讓程式以管理員方式執行。 (在商業軟體中,其實應該儘量避免以管理員身份執行。在安裝或配置時,提前授予將相應許可權。) 做法: 以C#專案為例: 1) 選擇專案,右鍵 -> 屬性 -> 安全性 -&

VS2017中設定程式管理員身份執行

    在Windows程式設計中,執行程式時出現錯誤,錯誤返回值為5,這表示程式執行的許可權不夠,在Visual Studio 2017 中設定程式以管理員身份執行的步驟是:直接專案右鍵---屬性--

程式自動管理員身份執行

C#: 1) 開啟Vs2005或vs2008工程,看在Properties下是否有app.manifest這個檔案;如沒有,右擊工程在選單中選擇“屬性”,   選中"Security",在介面中勾選"Enable ClickOnce Security Settings"後

如何自動管理員身份執行.NET程式

    windows 7和vista提高的系統的安全性,同時需要明確指定“以管理員身份執行”才可賦予被執行軟體比較高階的許可權, 比如訪問登錄檔等。否則,當以普通身份執行的程式需要訪問較高階的系統資源時,將會丟擲異常。   如何讓程式在啟動時,自動要求“管理員”許可權了,

Lsrunase普通域用戶管理員身份執行某個軟件

exe nas pil mpi -o strong window spa 方法 應用場景:例如金蝶軟件的有些功能必須使用管理員身份執行方可使用 使用方法:1. 將lsrunase文件夾內的lsrunase.exe復制到電腦的C:\Windows\System32下2

如何在DOS下管理員身份執行命令?

管理員 info -s ont window 命令 com 管理 轉換 原創 普通User的DOS窗口: 以管理員身份運行的DOS窗口: 轉換(Windows10系統下): 13:11:55 2018-10-18如何在DOS下以管理員身份執行命令?

win7系統設定cmd視窗預設管理員許可權執行

使用dos命令視窗開啟或者使用系統服務時,總會彈出“此操作需要管理員許可權”、“此項操作需要提升”,然後又苦逼的找到cmd.exe右鍵選擇以管理員許可權執行,這裡記錄一下使cmd命令預設以管理員許可權執行的設定操作。 一·直接修改登錄檔 使用win+R組合鍵,輸入 regedit

Ubuntu伺服器中建立新使用者並且允許該使用者管理員身份執行指令

目錄 1. 新建可登入圖形使用者介面的使用者 2. 允許該使用者以管理員身份執行指令 sudo” 是Unix/Linux平臺上的一個非常有用的工具,允許為非根使用者賦予一些合理的“權利”,讓他們執行一些只有根使用者或特許使用者才能完成的任務,從而減少根使用者的登陸次數和管理

管理員身份執行bat指令碼時,獲取當前檔案所在目錄

以管理員身份執行bat指令碼時,獲取當前檔案所在目錄     知道windows的bat指令碼很強大,但是具體命令向來很少接觸,今天在win7上執行自己以前寫的一個安裝mysql資料庫到系統服務的指令碼時,遇到一些問題,下面記錄一下。<?xml:namespa

結合VBS,實現批處理自動管理員身份執行

這是我在百度回答知友時寫的,用於自動以管理員身份執行命令或程式→百度原址 批處理程式碼,功能:自動以管理員身份執行 test.exe: MS DOS start admin.vbs runas /user:administrator test.e