我們知道,在Windows Vista ,微軟系列操作系統中加入了“UAC”權限控制。這是一個顯著的安全性能的提升。
在這以後的系統中軟件默認使用普通用戶方式運行,除非軟件聲明要求使用管理員方式運行,或者用戶強制使用管理員方式運行。
那麼我們在做一些敏感功能的時候,比如結束進程、讀寫內存、更改系統文件、更改系統設置等操作的時候,就需要提供管理員權限,否則無法獲取對象。這時就需要我們手動的,顯式的聲明程序需要管理員權限運行。那麼,我們又如何做到呢?
這裏引用微軟MSDN的說法:
右鍵你的工程,新建一個mainfest(應用程序清單)文件,
<!-- UAC 清單選項
如果要更改 Windows 用戶帳戶控制級別,請用以下節點之一替換
requestedExecutionLevel 節點。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
指定 requestedExecutionLevel 節點將會禁用文件和註冊表虛擬化。
如果要利用文件和註冊表虛擬化實現向後
兼容性,則刪除 requestedExecutionLevel 節點。
-->
將 <requestedExecutionLevel level="asInvoker" uiAccess="false" />設置爲requireAdministrator後,保存運行。當程序需要管理員權限時,就會提示用戶是否允許。
這個是一種方法,還有另外一個方法,是我經常用的。這個需要寫在Program.cs裏面。
1: static void 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:12: System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
13: //判斷當前登錄用戶是否爲管理員
14: if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
15: {16: //如果是管理員,則直接運行
17:18: Application.EnableVisualStyles();19: Application.Run(new Form1());
20: }21: else
22: {23: //創建啓動對象
24: System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
25: //設置運行文件
26: startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;27: //設置啓動參數
28: startInfo.Arguments = String.Join(" ", Args);
29: //設置啓動動作,確保以管理員身份運行
30: startInfo.Verb = "runas";
31: //如果不是管理員,則啓動UAC
32: System.Diagnostics.Process.Start(startInfo);33: //退出
34: System.Windows.Forms.Application.Exit();35: }36: }