shiy720 发表于 2024-6-7 17:08:44

C# 管理员身份执行cmd任务


C# 中有多种方式来以管理员身份执行 cmd 任务,下面都是可行的解决方案:

使用 Process 类
using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
      // 创建一个新进程
      Process process = new Process();

      // 设置命令和参数
      process.StartInfo.FileName = "cmd.exe";
      process.StartInfo.Arguments = "/c dir"; // 执行 dir 命令
      process.StartInfo.Verb = "runas"; // 以管理员身份运行
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.RedirectStandardOutput = true;

      // 启动进程
      process.Start();

      // 读取输出
      string output = process.StandardOutput.ReadToEnd();
      Console.WriteLine(output);

      // 等待进程结束
      process.WaitForExit();
    }
}
在上面的代码中,我们创建了一个新的 Process 对象,并设置了命令和参数。我们使用 Verb 属性将命令设置为以管理员身份运行,然后启动进程并读取输出。

使用 Elevate 类库
using Elevate;

class Program
{
    static void Main()
    {
      // 以管理员身份执行 cmd 命令
      Elevate.RunWithElevation("cmd.exe", "/c dir");
    }
}
在上面的代码中,我们使用了 Elevate 类库来以管理员身份执行 cmd 命令。

使用 ShellExecute 函数
using System;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
      // 以管理员身份执行 cmd 命令
      ShellExecute(IntPtr.Zero, "runas", "cmd.exe", "/c dir", null, SW_SHOW);
    }

   
    static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
    const int SW_SHOW = 5;
}
在上面的代码中,我们使用了 ShellExecute 函数来以管理员身份执行 cmd 命令。

使用 WindowsIdentity 和 WindowsPrincipal 类
using System;
using System.Security.Principal;

class Program
{
    static void Main()
    {
      // 获取当前用户的身份
      WindowsIdentity identity = WindowsIdentity.GetCurrent();

      // 创建一个新的 WindowsPrincipal 对象
      WindowsPrincipal principal = new WindowsPrincipal(identity);

      // 以管理员身份执行 cmd 命令
      if (principal.IsInRole(WindowsBuiltInRole.Administrator))
      {
            Process.Start("cmd.exe", "/c dir");
      }
      else
      {
            // 如果当前用户不是管理员,则提示错误
            Console.WriteLine("You are not an administrator.");
      }
    }
}
在上面的代码中,我们使用 WindowsIdentity 和 WindowsPrincipal 类来检查当前用户是否是管理员,如果是,则以管理员身份执行 cmd 命令。

这些方法都可以用来以管理员身份执行 cmd 任务,但是需要注意的是,以管理员身份运行程序可能会引发安全问题
页: [1]
查看完整版本: C# 管理员身份执行cmd任务