Win7 C# 控制檯程式寫登錄檔被拒,需要以管理員身份執行。
最近寫了一個控制檯程式,將程式的相關資訊註冊到登錄檔中。但是執行的時候提示寫登錄檔被拒。電腦的當前使用者沒有管理員的許可權。
如何給控制檯程式賦管理員的許可權呢?
給程式新增 .manifest 檔案:應用程式的Manifests則用於描述隔離應用程式,它管理著此應用程式在執行時要繫結的共享的並行元件的名字、版本。該Manifests可以作為一個檔案(.manifest檔案)儲存在應用程式相同的目錄下,也可以作為一種資源嵌入在可執行檔案內部(Embed Manifest)。
1、通過屬性介面載入。
首先檢查 VS2010 的【Properties
勾選中【Security】頁面中的【Enable ClickOnce Security Settings】節點(如下圖)。會在【Properties】下就有自動生成【app.manifest】檔案(如右上圖)。
雙擊開啟【app.manifest】檔案,將
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
改為
<requestedExecutionLevel level="requireAdministrator
asInvoker : 應用程式就是以當前的許可權執行。
highestAvailable: 以當前使用者可以獲得的最高許可權執行。
requireAdministrator: 以系統管理員許可權執行。
修改後的檔案如下:
然後再勾去【Security】中【Enable ClickOnce Security Settings】後,重新編譯即可。
2、通過新增新項新增:
通過這種方式新增的app.manifest不是位於【Properties】節點下;而是位於【Properties】的同級目錄下。
雙擊開啟【app.manifest】檔案,將
<requestedExecutionLevel level="asInvoker
改為
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
即可。
附:如果是WinFrom 窗體應用程式:可以通過程式碼來實現“以管理員身份執行”(轉)
static void Main(string[] Args)
{
/**
* 當前使用者是管理員的時候,直接啟動應用程式
* 如果不是管理員,則使用啟動物件啟動程式,以確保使用管理員身份執行
*/
//獲得當前登入的Windows使用者標示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//建立Windows使用者主題
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判斷當前登入使用者是否為管理員
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理員,則直接執行
Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
//建立啟動物件
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//設定執行檔案
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//設定啟動引數
startInfo.Arguments = String.Join(" ", Args);
//設定啟動動作,確保以管理員身份執行
startInfo.Verb = "runas";
//如果不是管理員,則啟動UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}