Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating an application programmatically using a file path in vb.net

I want to terminate an application using the full file path via vb.net, yet I could not find it under Process. I was hoping for an easy Process.Stop(filepath), like with Process.Start, but no such luck.

How can I do so?

like image 927
Cyclone Avatar asked Sep 09 '09 21:09

Cyclone


People also ask

How do I terminate an application in VB net?

Just Close() all active/existing forms and the application should exit. ok.


1 Answers

You would have to look into each process' Modules property, and, in turn, check the filenames against your desired path.

Here's an example:

VB.NET

    Dim path As String = "C:\Program Files\Ultrapico\Expresso\Expresso.exe"
    Dim matchingProcesses = New List(Of Process)

    For Each process As Process In process.GetProcesses()
        For Each m As ProcessModule In process.Modules
            If String.Compare(m.FileName, path, StringComparison.InvariantCultureIgnoreCase) = 0 Then
                matchingProcesses.Add(process)
                Exit For
            End If
        Next
    Next

    For Each p As Process In matchingProcesses
        p.Kill()
    Next

C#

string path = @"C:\Program Files\Ultrapico\Expresso\Expresso.exe";
var matchingProcesses = new List<Process>();
foreach (Process process in Process.GetProcesses())
{
    foreach (ProcessModule m in process.Modules)
    {
        if (String.Compare(m.FileName, path, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            matchingProcesses.Add(process);
            break;
        }
    }
}

matchingProcesses.ForEach(p => p.Kill());

EDIT: updated the code to take case sensitivity into account for string comparisons.

like image 62
Ahmad Mageed Avatar answered Sep 21 '22 20:09

Ahmad Mageed