2

编程新手,我正在编写一个应该打开 cmd 提示符的进程,运行命令

"/k nslookup 123.123.123.123;

然后将标准输出重定向到一个字符串,以便可以操作数据。我尝试了各种组合,但除了最后一行“按任意键关闭”之外,无法让程序输出任何内容。

我觉得好像我错过了一些非常简单的东西,因为我找不到我的代码有什么问题。有没有人有什么建议?

try
        {
            string strCmdText;
            strCmdText = "/k nslookup 123.123.123.123";

            // Start the process.
            Process p = new Process();

            //The name of the application to start, or the name of a document 
            p.StartInfo.FileName = "C:/Windows/System32/cmd.exe";
            // On start run the string strCmdText as a command
            p.StartInfo.Arguments = strCmdText;

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;   

            p.Start();

            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadLine();
            p.WaitForExit();
            Console.WriteLine(output);

        }
        catch (Exception)
        {
            Console.WriteLine( "error");
        }

//Wait for user to press a button to close window
        Console.WriteLine("Press any key...");
        Console.ReadLine();
4

1 回答 1

0

我认为这是因为命令提示符没有退出。不要传递参数,而是将它们写入标准输入然后退出,如下所示:

        p.StartInfo.Arguments = "";

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.CreateNoWindow = true;   

        p.Start();

        p.StandardInput.WriteLine("/k nslookup 123.123.123.123");
        p.StandardInput.WriteLine("exit");

        // Read the output stream first and then wait.
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        Console.WriteLine(output);
于 2013-08-02T13:11:52.257 回答