日期:2014-05-18  浏览次数:21139 次

使用cmd执行nslookup命令返回结果StandardOutput.ReadToEnd读取不全是什么原因??在线等待。。
我想使用cmd命令来执行nslookup命令,把运行结果读取出来,但是在某些时候读出来的结果不全,请问是什么原因??
代码是这样的:
string dosCommand = "nslookup www.sohkdindjf.com 8.8.8.8 ";
  Process p = new Process(); //创建进程对象  
  p.StartInfo.FileName = "cmd.exe"; //设定需要执行的命令
  p.StartInfo.Arguments = " /C " + dosCommand; //设定参数,其中的“/C”表示执行完命令后马上退出
  p.StartInfo.UseShellExecute = false; //不使用系统外壳程序启动
  p.StartInfo.RedirectStandardInput = true; //重定向输入
  p.StartInfo.RedirectStandardOutput = true; //重定向输出
  p.StartInfo.RedirectStandardError = true; //重定向错误
  p.StartInfo.CreateNoWindow = true; //不创建窗口
   
  try
  {
  if (p.Start()) //开始进程
  {
  if (milliseconds == 0)
  p.WaitForExit(); //这里无限等待进程结束
  else
  p.WaitForExit(milliseconds); //这里等待进程结束,等待时间为指定的毫秒

  output = p.StandardOutput.ReadToEnd(); //读取进程的输出 
   
  }
  }
  catch
  { }
  finally
  {
  if (p != null)
  p.Close();
  }
  }
  return output;
output的结果是:
"服务器: google-public-dns-a.google.com\r\nAddress: 8.8.8.8\r\n\r\n"

但是如果在cmd命令窗口执行结果应该是这样的:
服务器: google-public-dns-a.google.com
Address: 8.8.8.8

*** google-public-dns-a.google.com 找不到 www.sohkdindjf.com: Non-existent domain

两个显示的内容不一样,怎么是C#程序里output读出的结果与在cmd命令窗口执行的结果一样?? 或者C#有什么类可以执行nslookup一样的功能?

------解决方案--------------------
Process nslookup = new Process()
{
StartInfo = new ProcessStartInfo("nslookup")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
nslookup.Start();

nslookup.StandardInput.WriteLine("set type=srv");
nslookup.StandardInput.WriteLine("");
nslookup.StandardInput.Flush();
StringBuilder output = new StringBuilder();
while (nslookup.StandardOutput.Peek() > 0)
{
output.AppendFormat("{0}\n", nslookup.StandardOutput.ReadLine());
}
 或
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
IPAddress[] ips = hostEntry.AddressList;

------解决方案--------------------
其实是你执行出错了。。。那是error不是Output
------解决方案--------------------
p.StandardError.ReadToEnd()