找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 49|回复: 0

[工具类] C# 管理员身份执行cmd任务

[复制链接] IP属地:广东省广州市荔湾区
发表于 2024-6-7 17:08:44 | 显示全部楼层 |阅读模式

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

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

  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         // 创建一个新进程
  8.         Process process = new Process();

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

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

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

  20.         // 等待进程结束
  21.         process.WaitForExit();
  22.     }
  23. }
复制代码

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

使用 Elevate 类库
using Elevate;

  1. class Program
  2. {
  3.     static void Main()
  4.     {
  5.         // 以管理员身份执行 cmd 命令
  6.         Elevate.RunWithElevation("cmd.exe", "/c dir");
  7.     }
  8. }
复制代码

在上面的代码中,我们使用了 Elevate 类库来以管理员身份执行 cmd 命令。

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

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

  10.     [DllImport("shell32.dll")]
  11.     static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
  12.     const int SW_SHOW = 5;
  13. }
复制代码

在上面的代码中,我们使用了 ShellExecute 函数来以管理员身份执行 cmd 命令。

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

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

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

  11.         // 以管理员身份执行 cmd 命令
  12.         if (principal.IsInRole(WindowsBuiltInRole.Administrator))
  13.         {
  14.             Process.Start("cmd.exe", "/c dir");
  15.         }
  16.         else
  17.         {
  18.             // 如果当前用户不是管理员,则提示错误
  19.             Console.WriteLine("You are not an administrator.");
  20.         }
  21.     }
  22. }
复制代码

在上面的代码中,我们使用 WindowsIdentity 和 WindowsPrincipal 类来检查当前用户是否是管理员,如果是,则以管理员身份执行 cmd 命令。

这些方法都可以用来以管理员身份执行 cmd 任务,但是需要注意的是,以管理员身份运行程序可能会引发安全问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-9-17 04:28 , Processed in 0.605178 second(s), 22 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表