2013-07-31 40 views
1

編程新手,但我想知道如果我想要做甚至是可能的!如果是的話如何?將來自Cmd Promt Window的信息複製到控制檯應用程序中

我開發了一個控制檯應用程序,它可以獲取計算機的IP地址。程序然後打開cmd提示符並運行nslookup(使用所述IP地址)來獲取關於計算機的一些信息。

當程序結束時,我有兩個控制檯窗口打開; cmd promt控制檯和程序控制臺。 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(); 
     } 
    } 
} 

回答

0

您正在開始一個外部過程,這很好。你現在需要做的是重定向標準輸出。而不是從cmd提示窗口複製信息,您只需要將它反饋到您的程序中。你必須做一些解析的,但這裏的來自微軟的樣本:

// 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

相關問題