1

I am having a text file in this path "C:\Test\test.txt" when this was openeed I need to close this.

When I am trying to use the below code all the instances of notepad are closing and I don't want that to be happened and I want to close only the ".txt" file:

Any help would be appreciated!

Here is my code:

 Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")
  For Each p As Process In Process
    p.Kill()
Next 

2 Answers2

2

You can look at the

Process.MainWindowTitle

property of p.

Notepad's title will be Filename.txt - Notepad

If you started the process yourself, you can kill it using the Process.Kill() method.

Note that in many (most?) circumstances, killing all instances of a process isn't really a good user experience since the user may have started instances of that process on their own in addition to the instance your program launched / is attempting to close.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Thanks for your reply and can you provide me a sample code for that. –  Jul 15 '11 at 18:18
  • No actually I am trying to write it to the file and while writing I need to check if the file is opened and then I need to close it and write the text to it. –  Jul 15 '11 at 18:25
1

You could do something as mentioned about using an if statement. Assuming you opened the file called test.

 Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")      
    For Each p As Process In Process
        If p.MainWindowTitle.Contains("test") Then
            p.Kill()
        End If
    Next

EDIT:

To check for multiple files

simply add or to the .Contains line

If p.MainWindowTitle.Contains("test") Or ("blahblah") Then
p.kill()
sealz
  • 5,348
  • 5
  • 40
  • 70