码迷,mamicode.com
首页 > Windows程序 > 详细

C#编写以管理员身份运行的程序

时间:2015-02-28 11:38:51      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:principal   windows   identity   管理员   应用程序   

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();
 
            }
 
        }
 
    }
 
}


本文出自 “灵雨飘零博客” 博客,请务必保留此出处http://kingrain.blog.51cto.com/91779/1615852

C#编写以管理员身份运行的程序

标签:principal   windows   identity   管理员   应用程序   

原文地址:http://kingrain.blog.51cto.com/91779/1615852

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!