关闭由 c# 运行的批处理文件

本文关键字:批处理文件 运行 | 更新日期: 2023-09-27 18:34:54

>我有一个在给定端口和主机上运行漏洞扫描的 simpel 程序。现在,我必须找到一种方法来关闭从 c# 窗体运行的批处理文件。我必须能够从按钮关闭批处理文件,即使它还没有完成。而且我毫无头绪,也没有找到方法。

编辑:添加了更多代码,但仍然给出错误"当前上下文中不存在进程">

private void button10_Click(object sender, EventArgs e)
    {
        if (button10.Text == "Scan")
        {
            int port = (int)numericUpDown2.Value;
            string path = Directory.GetCurrentDirectory();
            string strCommand = path + "/SystemFiles/nikto/nikto.bat";
            string host = textBox5.Text;
            Console.WriteLine(strCommand);
            richTextBox5.Text += "Starting Nikto Vulnerability Scan On " + host + " On Port " + port + System.Environment.NewLine;
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = strCommand;
            startInfo.Arguments = "-h " + host + " -port " + port + textBox6.Text;
            process.StartInfo = startInfo;
            process.Start();
            richTextBox5.Text += "Vulnerability Scan Started On " + host + " On Port " + port + System.Environment.NewLine;
            button10.Text = "Cancel";
        }
        else
        {
            process.Kill();
            button10.Text = "Scan";
        }

    }

关闭由 c# 运行的批处理文件

您可以在进程对象中使用方法 kill

process.Kill()

这是完整的答案。

public partial class Form1 : Form
{
    private System.Diagnostics.Process _process;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        if (_process == null || _process.HasExited)
        {
            _process = new Process();
        }
        else
        {
            _process.Kill();
            _process = null;                
            button10.Text = "Scan";
            return;
        }
        int port = (int)numericUpDown2.Value;
        string path = Directory.GetCurrentDirectory();
        string strCommand = path + "/SystemFiles/nikto/nikto.bat";
        string host = textBox5.Text;
        Console.WriteLine(strCommand);
        richTextBox5.Text += "Starting Nikto Vulnerability Scan On " + host + " On Port " + port + System.Environment.NewLine;
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = strCommand,
            Arguments = "-h " + host + " -port " + port + textBox6.Text
        };
        _process.StartInfo = startInfo;
        _process.Start();
        richTextBox5.Text += "Vulnerability Scan Started On " + host + " On Port " + port + System.Environment.NewLine;
        button10.Text = "Cancel";
    }
}