C#管理员身份运行程序 C#中用管理员身份运行程序代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#管理员身份运行程序 C#中用管理员身份运行程序代码实例

  2021-03-21 我要评论
想了解C#中用管理员身份运行程序代码实例的相关内容吗,在本文为您仔细讲解C#管理员身份运行程序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,管理员身份,运行程序,下面大家一起来学习吧。
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();

      }

    }

  }

}
  

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们