在没有窗口的情况下从C#运行命令行并获取输出 [英] Running Command Line from C# without Window and Getting Output

查看:162
本文介绍了在没有窗口的情况下从C#运行命令行并获取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C#运行命令行脚本。我希望它在没有外壳的情况下运行并将输出放入我的字符串输出中。它不喜欢p.StartInfo行。我究竟做错了什么?我没有运行像p.StartInfo.FileName = YOURBATCHFILE.bat这样的文件,例如方法:在C#中执行命令行,获取STD OUT结果。我需要设置 CMD.exe和命令行字符串。我已经尝试过p.Start( CMD.exe,strCmdText);但这给了我错误: Memer'System.Diagnostics.Process.Start(string,string)'无法通过实例引用进行访问;而应使用类型名称对其进行限定。

I am trying to run a command line script from C#. I want it to run without a shell and place the output into my string output. It doesn't like the p.StartInfo line. What am I doing wrong? I am not running a file like p.StartInfo.FileName = "YOURBATCHFILE.bat" like How To: Execute command line in C#, get STD OUT results. I need to set the "CMD.exe" and command line string. I have tried p.Start("CMD.exe", strCmdText); but that gives me the error: "Memer 'System.Diagnostics.Process.Start(string,string)' cannot be accessed with an instance reference; qualify it with a type name instead."

    string ipAddress;
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    string strCmdText;
    strCmdText = "tracert -d " + ipAdress;
    p.StartInfo("CMD.exe", strCmdText);
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();


推荐答案

此代码为我提供了正确的输出。

This code gives me the correct ouput.

const string ipAddress = "127.0.0.1";
Process process = new Process
{
    StartInfo =
    {
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true,
        FileName = "cmd.exe",
        Arguments = "/C tracert -d " + ipAddress
    }
};
process.Start();
process.WaitForExit();
if(process.HasExited)
{
    string output = process.StandardOutput.ReadToEnd();
}

这篇关于在没有窗口的情况下从C#运行命令行并获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆