C#編寫以管理員身份運行的程序

using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Windows.Forms;
 
 
 
namespace MyWebBrowser
 
{
 
    static class Program
 
    {
 
        /// <summary>
 
        /// 應用程序的主入口點。
 
        /// </summary>
 
        [STAThread]
 
        static void Main()
 
        {
 
            //獲得當前登錄的Windows用戶標示
 
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
 
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
 
            //判斷當前登錄用戶是否爲管理員
 
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
 
            {
 
                //如果是管理員,則直接運行
 
                Application.EnableVisualStyles();
 
                Application.SetCompatibleTextRenderingDefault(false);
 
                Application.Run(new Form1());
 
            }
 
            else
 
            {
 
                //創建啓動對象
 
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
 
                //設置運行文件
 
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
 
                //設置啓動動作,確保以管理員身份運行
 
                startInfo.Verb = "runas";
 
                //如果不是管理員,則啓動UAC
 
                System.Diagnostics.Process.Start(startInfo);
 
                //退出
 
                System.Windows.Forms.Application.Exit();
 
            }
 
        }
 
    }
 
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章