C#默認以管理員身份運行程序實現代碼

字號:


    權限不夠,導致無法修改系統(tǒng)時間,于是我以管理員身份運行了一次,結果測試成功,下面為大家介紹下C#如何默認以管理員身份運行程序
    上篇博客寫了一下如何通過網絡時間更新系統(tǒng)時間,當時寫的時候怎么測試都不成功,后來想想是不是我操作系統(tǒng)(當時是在win8上開發(fā)的)的問題。當時我猜應該是權限不夠,導致無法修改系統(tǒng)時間,于是我以管理員身份運行了一次,結果測試成功!原來真的是權限的問題,于是就在程序里面加入了默認以管理員身份運行的代碼。下面讓我們看看是怎么實現的吧!
    程序默認以管理員身份運行
    代碼如下:
    static void Main(string[] Args)
    {
    /**
    * 當前用戶是管理員的時候,直接啟動應用程序
    * 如果不是管理員,則使用啟動對象啟動程序,以確保使用管理員身份運行
    */
    //獲得當前登錄的Windows用戶標示
    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);
    //判斷當前登錄用戶是否為管理員
    if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
    {
    //如果是管理員,則直接運行
    Application.EnableVisualStyles();
    Application.Run(new Form1());
    }
    else
    {
    //創(chuàng)建啟動對象
    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();
    }
    }
    打開程序集里的Program.cs文件,并將其中Main方法中的代碼替換為以上代碼即可實現程序默認以管理員身份運行。