C# 讓程式自動以管理員身份執行

genweihua發表於2013-01-16
  
        轉載: http://tech.it168.com/a2011/0728/1224/000001224704_all.shtml
         2011年07月28日19:05 來源:Lemon_s的部落格 作者:Lemon_s 編輯:胡銘婭 評論:--

  【IT168 技術】exe在Vista或Win7下不以管理員許可權執行,會被UAC(使用者帳戶控制)阻止訪問系統某些功能,如修改登錄檔操作等;如何讓exe以管理員許可權執行呢,方法有兩種,一個是直接修改exe屬性;另一個是在程式中加入MANIFEST資源,下面分別介紹。

  1、直接修改exe屬性

  1) 右擊“exe”,在彈出的選單中選擇“屬性”,出現的介面如下圖:

  C# 讓程式自動以管理員身份執行

  2) 選擇"Compatibility"項,並勾選"Run this program as administrator"項即可。

  2、 在程式中加入MANIFEST資源

  1) 開啟Vs2005或vs2008工程,看在Properties下是否有app.manifest這個檔案;如沒有,右擊工程在選單中選擇“屬性”,出現介面如下圖:

  C# 讓程式自動以管理員身份執行


  選中"Security",在介面中勾選"Enable ClickOnce Security Settings"後,在Properties下就有自動生成app.manifest檔案。

  開啟app.manifest檔案,將

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

  改為

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

  修改後的app.manifest為:

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.



If you want to utilize File and Registry Virtualization for backward
compatibility then delete the requestedExecutionLevel node.
--&gt
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
requestedPrivileges>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
applicationRequestMinimum>
security>
trustInfo>
asmv1:assembly>

  然後在"Security"中再勾去"Enable ClickOnce Security Settings"後,重新編譯即可。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22275400/viewspace-752763/,如需轉載,請註明出處,否則將追究法律責任。

相關文章