c# - 重定向命令提示符的输出

标签 c# redirect process cmd nslookup

编程新手,我正在编写一个应该打开 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();

最佳答案

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

        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);

关于c# - 重定向命令提示符的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18017710/

相关文章:

c# - 运行 DELETE SQL 查询后 ASP.NET 页面不刷新

php - 如何捕获并记录使用 PHP 发生的任何 301 重定向 (.htaccess)

javascript - 根据选项重定向提交按钮

swift - 我不能在函数中使用 Process

linux - 在 linux 中递归地杀死带有子进程的 R 进程

c# - 在包含字典的类上公开 foreach

c# - 如何为 GoogleWebAuthorizationBroker.AuthorizeAsync 设置 return_uri?

c# - 关于异步/任务的初学者

python - 如何从根路径自动重定向?

c - 为什么 child 的 getppid() 返回 1