C#以普通权限启动外部程序

C#以普通权限启动外部程序

  1. 第一种,使用explorer.exe来启动外部程序

    Process.Start("Explorer.exe", fileName); //fileName为外部应用的路径
    

    这种方式启动外部程序虽然是普通权限,但是不能给外部程序传参,可能是我未找到方式,对于不需要传参的启动,这种方法最简便。

  2. 第二种,使用RunAs.exe来启动外部程序

    public void Run(string fileName, string arguments = null)
            {
                string cmd = fileName;
                if (!string.IsNullOrWhiteSpace(arguments))
                {
                    cmd = $""{fileName} {arguments}"";
                }
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.CreateNoWindow = true;
                psi.UseShellExecute = false;
                psi.FileName = "RunAs";
                psi.WorkingDirectory = System.IO.Path.GetDirectoryName(fileName);
                psi.Arguments = $"/trustlevel:0x20000 {cmd}";
                Process.Start(psi);
            }
    

    其中关键的是/trustlevel:0x20000。这种方式就可以传参了。

判断程序是否以管理员权限启动

 /// <summary>
        /// 判断程序是否以管理员权限运行
        /// </summary>
        /// <returns></returns>
        public static bool IsAdministrator()
        {
            System.Security.Principal.WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(current);
            return windowsPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
原文地址:https://www.cnblogs.com/zzr-stdio/p/14429877.html