tnblog
首页
视频
资源
登录

确保.net程序始终以管理员身份运行

2805人阅读 2018/12/13 15:49 总访问:15335 评论:0 收藏:0 手机
分类: DotNet捣鼓
  
            
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication17
    {
        class Program
        {
            static void Main(string[] args)
            {
                //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))
                {
                    //如果是管理员,则直接运行
                    Console.WriteLine("是管理员身份运行");
                    Console.Read();
                }
                else
                {
                    //如果是管理员,则直接运行
                    Console.WriteLine("不是管理员身份运行");
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute = true;
                    startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    //自己写入自己的程序路径
                    startInfo.FileName = Environment.CurrentDirectory + "//ConsoleApplication17.exe";
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch
                    {
                        return;
                    }
                    //退出
                    //Application.Exit();
                }
                
            }
        }
    }


评价
Amazing everday
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术