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

相关文章
相关标签/搜索