c#中程序以管理员身份运行的三种办法
三種辦法:
一、設(shè)置程序本身的屬性:勾選“以管理員身份運(yùn)行此程序”,必要時(shí)設(shè)置“更改所有用戶設(shè)置-以管理員身份運(yùn)行此程序”,當(dāng)然這種辦法是被動(dòng)的,也不是最實(shí)際的辦法;
二、代碼法:
static void Main(string[] Args)
? ? ? ? {
? ? ? ? ? ? /**
? ? ? ? ? ? ?* 當(dāng)前用戶是管理員的時(shí)候,直接啟動(dòng)應(yīng)用程序
? ? ? ? ? ? ?* 如果不是管理員,則使用啟動(dòng)對(duì)象啟動(dòng)程序,以確保使用管理員身份運(yùn)行
? ? ? ? ? ? ?*/
? ? ? ? ? ? //獲得當(dāng)前登錄的Windows用戶標(biāo)示
? ? ? ? ? ? System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
? ? ? ? ? ? //創(chuàng)建Windows用戶主題
? ? ? ? ? ? Application.EnableVisualStyles();
?
? ? ? ? ? ? System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
? ? ? ? ? ? //判斷當(dāng)前登錄用戶是否為管理員
? ? ? ? ? ? if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //如果是管理員,則直接運(yùn)行
?
? ? ? ? ? ? ? ? Application.EnableVisualStyles();
? ? ? ? ? ? ? ? Application.Run(new Form1());
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //創(chuàng)建啟動(dòng)對(duì)象
? ? ? ? ? ? ? ? System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
? ? ? ? ? ? ? ? //設(shè)置運(yùn)行文件
? ? ? ? ? ? ? ? startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
? ? ? ? ? ? ? ? //設(shè)置啟動(dòng)參數(shù)
? ? ? ? ? ? ? ? //startInfo.Arguments = String.Join(" ", Args);
? ? ? ? ? ? ? ? //設(shè)置啟動(dòng)動(dòng)作,確保以管理員身份運(yùn)行
? ? ? ? ? ? ? ? startInfo.Verb = "runas";
? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? //如果不是管理員,則啟動(dòng)UAC
? ? ? ? ? ? ? ? ? ? System.Diagnostics.Process.Start(startInfo);
? ? ? ? ? ? ? ? ? ? //退出
? ? ? ? ? ? ? ? ? ? System.Windows.Forms.Application.Exit();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch
? ? ? ? ? ? ? ? {?
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
三、配置法:
??vs2010中,項(xiàng)目右鍵屬性--安全性---啟用ClickOnce安全設(shè)置
?
??然后程序目錄下會(huì)生成一個(gè)app.manifest文件
?
??<requestedExecutionLevel level="asInvoker" uiAccess="false" />
改為
??<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
???
??然后在"安全性"中再勾去"啟用ClickOnce安全設(shè)置"后,重新編譯即可。
?
總結(jié)
以上是生活随笔為你收集整理的c#中程序以管理员身份运行的三种办法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#如何判断程序调用的exe已结束
- 下一篇: 在c#中将debug/release下文