0
点赞
收藏
分享

微信扫一扫

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

yeamy 2022-03-24 阅读 156
c#

在很多时候运行软件会弹出“是否以管理员身份运行”就很不舒服也很烦,所以今天给大家分享在代码里解决此问题。

 不用添加头部引用,直接把代码复制粘贴就可以使用了。


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                /**
                 * 当前用户是管理员的时候,直接启动应用程序
                 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
                 */
                //获得当前登录的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.Run(new Form1());
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute = true;
                    startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    startInfo.FileName = Application.ExecutablePath;
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch
                    {
                        return;
                    }
                    //退出
                    Application.Exit();
                }
            
举报

相关推荐

0 条评论