在Windows7上用C#判断程序是否以管理员身份运行

实际上就是在程序中判断当前用户是否属于管理员组。 在Windows7中直接运行程序,返回false。右键-以管理员身份运行,返回true。 class Program{static void M

实际上就是在程序中判断当前用户是否属于管理员组。
在Windows7中直接运行程序,返回false。右键-以管理员身份运行,返回true。

class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(isRunningAsAdmin());
            System.Console.ReadLine();
        }

        /// <summary>
        /// 判断程序是否以管理员身份运行
        /// </summary>
        /// <returns></returns>
        public static bool isRunningAsAdmin()
        {
            bool result = false;
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                result = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch(Exception e)
            {
                //log
                System.Console.WriteLine("error:" + e);
            }
            
            return result;
        }
    }

发布者:admin,转转请注明出处:http://www.yc00.com/web/1738939147a4086326.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信