1级标题
启动bat
private string _start; //bat路径
private void Awake()
{
_start = @"C:\test\test.bat";
RunBat(_start);
}
//启动bat
public void RunBat(string filename)
{
Process pro = new Process();
FileInfo file = new FileInfo(filename);
pro.StartInfo.WorkingDirectory = file.Directory.FullName;
pro.StartInfo.FileName = filename;
pro.StartInfo.CreateNoWindow = false;
//pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏启动窗口
pro.Start();
//pro.WaitForExit(); //等待启动完毕离开
}
//结束端口号的占用
private void t_btn_kill_Click()
{
int port =88;
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
List<int> list_pid = GetPidByPort(p, port);
if (list_pid.Count == 0)
{
return;
}
PidKill(p, list_pid);
}
private static void PidKill(Process p, List<int> list_pid)
{
p.Start();
foreach (var item in list_pid)
{
p.StandardInput.WriteLine("taskkill /pid " + item + " /f");
p.StandardInput.WriteLine("exit");
}
p.Close();
}
private static List<int> GetPidByPort(Process p, int port)
{
int result;
bool b = true;
p.Start();
p.StandardInput.WriteLine(string.Format("netstat -ano|find \"{0}\"", port));
p.StandardInput.WriteLine("exit");
StreamReader reader = p.StandardOutput;
string strLine = reader.ReadLine();
List<int> list_pid = new List<int>();
while (!reader.EndOfStream)
{
strLine = strLine.Trim();
if (strLine.Length > 0 && ((strLine.Contains("TCP") || strLine.Contains("UDP"))))
{
Regex r = new Regex(@"\s+");
string[] strArr = r.Split(strLine);
if (strArr.Length >= 4)
{
b = int.TryParse(strArr[3], out result);
if (b && !list_pid.Contains(result))
list_pid.Add(result);
}
}
strLine = reader.ReadLine();
}
p.WaitForExit();
reader.Close();
p.Close();
return list_pid;
}