#region Ping 返回true则代表可以连接成功 public 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().Replace("Request timed out", "无法访问目标主机"); if (pingResult.IndexOf("无法访问目标主机") == -1) { Flag = true; } proc.StandardOutput.Close(); } catch (Exception ex) { } finally { proc.Close(); proc.Dispose(); } return Flag; } #endregion
#region Connect 连接局域网 返回true则代表可以连接成功 public 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(); proc.StandardInput.WriteLine("net use * /del /y"); //中断开所有连接 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; } #endregion
时间: 2024-12-23 01:40:59