ClickOnce方式部署應用簡單方便,估計不少人都用過,但這種方式存在必定的「缺陷」,即以管理員方式啓動應用的問題,雖然出於安全考慮能夠理解,但給須要管理員權限才能正常運行的程序帶來了必定的麻煩,這致使部分人員放棄了ClickOnce發佈。安全
通過查找相關資料,發現仍是有辦法解決這個問題的,具體操做以下:app
一、修改 manifest 文件函數
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
經測試,若是應用程序沒有 manifest 文件的,能夠不用添加 app.manifest 文件,ClickOnce發佈後會生成以下格式的 manifest 文件:主程序文件名命名.manifest (例如:Mytest.exe.manifest)測試
自動生成的 manifest 文件中 requestedExecutionLevel 配置與上述一致。ui
但以上不排除是個例,若是不配置此項出現異常時可考慮增長此設置。spa
二、修改程序主函數(即「應用程序的主入口點」,例如: Program.cs 中的 Main 函數)code
using System; using System.Diagnostics; using System.Reflection; using System.Security.Principal; using System.Windows.Forms; namespace MyTest { static class Program { [STAThread] static void Main() { Action run = () => { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); }; WindowsIdentity wi = WindowsIdentity.GetCurrent(); bool runAsAdmin = wi != null && new WindowsPrincipal(wi).IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { try { //不可能以管理員方式直接啓動一個 ClickOnce 部署的應用程序,因此嘗試以管理員方式啓動一個新的進程 Process.Start(new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase) { UseShellExecute = true, Verb = "runas" }); } catch (Exception ex) { MessageBox.Show(string.Format("以管理員方式啓動失敗,將嘗試以普通方式啓動!{0}{1}", Environment.NewLine, ex), "出錯啦!", MessageBoxButtons.OK, MessageBoxIcon.Error); run();//以管理員方式啓動失敗,則嘗試普通方式啓動 } Application.Exit(); } else { run(); } } } }
原文地址:http://www.codeproject.com/Tips/627850/ClickOnce-deployment-vs-requestedExecutionLevel-eqorm