1

编程新手,但我想知道我想做的事情是否可能!如果是这样怎么办?

我开发了一个获取计算机 IP 地址的控制台应用程序。然后程序打开 cmd 提示符并运行 nslookup(使用所述 IP 地址)以获取有关计算机的一些信息。

当程序结束时,我打开了两个控制台窗口;cmd 提示控制台和程序控制台。cmd 提示符有我需要的信息。我不知道如何从 cmd 控制台复制/获取信息并将其放入字符串/数组中,以便我可以使用这些信息。

我已经搜索了谷歌,但我一直得到的只是从 cmd 提示窗口手动复制的方法!不是如何从一个程序打开的 cmd 提示窗口返回信息!

另外请不要建议进行反向 DNS 查找或使用 environment.machinename 而不是使用 cmd 提示符。我尝试了很多方法,这是我能够访问我需要的正确信息的唯一方法。

using System;
using System.Net;
using System.Net.Sockets;


namespace ProcessService
{
    static class Program
    {

        static void Main()
        {

            //The IP or Host Entry to lookup
            IPHostEntry host;
            //The IP Address String
            string localIP = "";
            //DNS lookup
            host = Dns.GetHostEntry(Dns.GetHostName());
            //Computer could have several IP addresses,iterate the collection of them to find the proper one
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }

            //Converts an IP address string to an IPAddress instance.
            IPAddress address = IPAddress.Parse(localIP);


            string strCmdText;
            strCmdText = "/k nslookup " + localIP;
            //open cmd prompt and run the command nslookup for a given IP
            System.Diagnostics.Process.Start("C:/Windows/System32/cmd.exe", strCmdText);


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

1 回答 1

0

您正在启动一个外部进程,这很好。您现在需要做的是重定向标准输出。与其从 cmd 提示符窗口复制信息,不如将其反馈到您的程序中。您必须进行一些解析,但这是来自 microsoft 的示例:

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

来源:http: //msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

于 2013-07-31T17:12:33.877 回答