///
kongxiang--2013.7.23
/// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace ping2 { class Program { //返回true则代表可以ping成功 //remoteHost为对方IP public static bool Ping(string remoteHost) { bool Flag = false; Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = @"ping -n 1 " + remoteHost; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(500); } string pingResult = proc.StandardOutput.ReadToEnd(); if (pingResult.IndexOf("(0% loss)") != -1) { Flag = true; } proc.StandardOutput.Close(); } catch (Exception ex) { } finally { proc.Close(); proc.Dispose(); } return Flag; } //返回true则代表可以连接成功 //remoteHost为对方IP userName为用户名 passWord为密码 public static bool Connect(string remoteHost, string userName, string passWord) { bool Flag = false; Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = @"net use //" + remoteHost + " " + passWord + " " + " /user:" + userName + ">NUL"; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (String.IsNullOrEmpty(errormsg)) { Flag = true; } } catch (Exception ex) { } finally { proc.Close(); proc.Dispose(); } return Flag; } static void Main(string[] args) { String strIP = "127.0.0.1"; Console.WriteLine("Ping Result:{0}", Ping(strIP)); Console.WriteLine("Connect Result:{0}", Connect("127.0.0.1", "rocher", "123456")); Console.Read(); } } }