使用参数和集合输出启动命令行

时间:2014-04-11 00:41:01

标签: c# command-line

ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "tsvc -a -st rifs -h "+textBox1+" -sn "+textBox2+" -status";

Process process = new Process();
process.StartInfo = startInfo;
process.Start();

richTextBox1.Text = process.StandardOutput.ReadToEnd();
  1. 我需要在cmd中运行一个命令,该命令将使用2个参数插入到textBox1和textBox2中,然后将输出发送到richTextBox1。

  2. 以这种方式运行时,我得到:

      

    System.dll中发生'System.InvalidOperationException'类型的第一次机会异常   其他信息:StandardOut尚未重定向或进程尚未开始

  3. 我试图排除输出行,当我这样做时确实运行CMD但没有输入任何命令(它只是打开一个CMD窗口而什么都不做)。

2 个答案:

答案 0 :(得分:1)

Process.Start()异步启动一个新进程。当你到达process.StandardOutput.ReadToEnd()时,该过程尚未完成,因此异常。您应该使用eventing挂钩到OutputDataRecieved事件。你想做这样的事情:

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1 + " -sn " + textBox2 + " -status";

        process.StartInfo = startInfo;
        process.OutputDataReceived += ProcessOnOutputDataReceived;
        process.ErrorDataReceived += ProcessOnOutputDataReceived;
        process.Start();

然后将事件处理程序添加到收到的输出数据中,如下所示:

    private void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
    {
        richTextBox1.Text += dataReceivedEventArgs.Data;
    }

另外,我不确定,但我认为您需要在文本框中调用文本:

startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1.Text + " -sn " + textBox2.Text + " -status";

答案 1 :(得分:0)

管理到最后用。

        richTextBox1.Text = "";
        int counter = 0 ,totalMemory=0;
        string line;
        string command = " /c ro -a -h " + textBox1.Text + " -sn HC* $$info Server Total = $servermemory Service Memory = $servicememory > c:\\noc\\ntb\\logs\\output.txt";
        ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
        Process proc = new Process();
        procStartInfo.CreateNoWindow = true;
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.RedirectStandardError = true;
        procStartInfo.UseShellExecute = false;
        proc.StartInfo = procStartInfo;
        proc.Start();
        proc.WaitForExit();