You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#无需调用cmd.exe直接运行Windows命令

方案1:直接调用目标可执行文件(推荐)

你要运行的whoami本身是Windows自带的独立可执行程序,无需依赖cmd/powershell即可直接启动,使用Process类调用即可,完全符合不直接调用cmd/powershell的要求:

using System.Diagnostics;

// 封装调用方法
public static string RunSystemCommand(string exeName, string args = "")
{
    var startInfo = new ProcessStartInfo
    {
        FileName = exeName,
        Arguments = args,
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = true
    };

    using var process = Process.Start(startInfo);
    process.WaitForExit();
    return process.StandardOutput.ReadToEnd();
}

// 调用示例
string whoamiOutput = RunSystemCommand("whoami.exe");

方案2:调用WScript.Shell COM对象(和VB实现逻辑一致)

如果需要和VB的CreateObject("WScript.Shell")实现逻辑对齐,可以通过C#的COM互操作直接调用该对象,不需要触发cmd/powershell调用:

using System.Runtime.InteropServices;

// 动态创建WScript.Shell COM对象,无需提前添加项目引用
Type shellType = Type.GetTypeFromProgID("WScript.Shell");
dynamic shellInstance = Activator.CreateInstance(shellType);

// 执行命令
var execResult = shellInstance.Exec("whoami");
string output = execResult.StdOut.ReadAll();

// 释放COM对象避免资源泄漏
Marshal.ReleaseComObject(shellInstance);

注意事项

  • 两个方案都不会直接调用cmd.exe或powershell.exe,满足核心要求
  • 如果你要运行的是cmd内置命令(如dir、copy这类没有独立exe的命令),才需要依赖shell执行,独立可执行程序优先选择方案1,稳定性更高

内容的提问来源于stack exchange,提问作者TheHidden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:15:08