使用C#执行bat文件和结束某个端口号

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值