C#默認以管理員身份運行程序

因爲WIN8的權限限制,不少程序安裝後沒有寫入權限,致使程序沒法正常運行,如下是讓程序以管理員身份運行,解決此問題ide

static void Main(string[] Args)
        {
            /**
             * 當前用戶是管理員的時候,直接啓動應用程序
             * 若是不是管理員,則使用啓動對象啓動程序,以確保使用管理員身份運行
             */
            //得到當前登陸的Windows用戶標示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //建立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
            {
                //建立啓動對象
                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方法中的代碼替換爲以上代碼便可實現程序默認以管理員身份運行。ui

相關文章
相關標籤/搜索