views:

643

answers:

2

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?

+1  A: 

try

System.Diagnostics.Process.GetProcessesByName(nameOfExeFile).First().Kill()

This ignores the path of the file.

Esben Skov Pedersen
Any way to do it *with* the path though? Or, is there any way to find out the name of the file from the file path?
Cyclone
+1  A: 

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.

Ahmad Mageed
My application is in vb.net, I think your example was in c#. I am not very fluent in c#, so I cannot port this.
Cyclone
Added the vb.net code to my post.
Ahmad Mageed
That ought to work, thanks!
Cyclone
It worked!
Cyclone
@Cyclone: no prob! BTW, I updated the code to ignore case sensitivity during the filepath comparison. Otherwise, you would've needed to pass in the path with the same case as the one defined in the module.
Ahmad Mageed
Okay! Thanks!!
Cyclone