微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

代码

using System;
 System.Collections.Generic;
 System.Linq;
 System.Windows.Forms;

namespace MyWebbrowser
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        </summary>
        [STAThread]
        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( Form1());
            }
            else
            {
                创建启动对象 
                System.Diagnostics.processstartinfo startInfo =  System.Diagnostics.processstartinfo();
                设置运行文件 
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                设置启动动作,确保以管理员身份运行 
                startInfo.Verb = "runas";
                如果不是管理员,则启动UAC 
                System.Diagnostics.Process.Start(startInfo);
                退出 
                System.Windows.Forms.Application.Exit();
            }
        }
    }
}
View Code

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐