0
点赞
收藏
分享

微信扫一扫

C#调用Windows cmd那些事【内含踩坑秘籍】

有时候,在开发过程中会遇到一些问题,比如获取系统的一些东西:物理网卡地址、CPU 信息等。使用微软相关库会遇到跨平台、微软相关环境的问题,在此,你不如来试试通过cmd执行命令行获取。

C#为例,先说一下平台判断吧。

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    // TODO Windows平台这么干
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    // TODO Linux平台这么干
}

Windows平台这么执行cmd命令:

/// <summary>
/// 命令行执行
/// </summary>
/// <param name="cmd">待执行命令行</param>
/// <returns>string</returns>
private static string InvokeCmd(string cmdArgs)
{
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();

    p.StandardInput.WriteLine(cmdArgs);
    p.StandardInput.WriteLine("exit");
    string Tstr = p.StandardOutput.ReadToEnd();
    p.Close();
    return Tstr;
}

Windows平台这么执行cmd怎么调用呢?

try
{
    // 待执行的命令
    string cmdStr = "";
    // 获取执行结果
    string Str = InvokeCmd(cmdStr);
    // 按行处理执行结果
    string[] Shows = Str.Split("\n");
    // TODO
}
catch (Exception e)
{
    // 异常了写点日志,日志代码这里就不贴了
    LogUtils.WriteLog("异常:" + e.Message);
    return "";
}

结束。

那是不可能的,下面上踩坑秘籍:

1、C++实现 会有一个黑框一闪而过,不建议使用。

2、有时候获取不到数据

可能是没有调用到相关命令

可以在cmd中运行一下你执行的命令,就像这样:

 然后提示说不是内部命令,也不是可运行程序或批处理文件。

只需要找到计算机中该命令位置,配置到环境变量Path即可。

举报

相关推荐

0 条评论