0

I need to open text files programatically using vb.net after overwriting the existing file. However, if the file is already open, the old version of the file is still displayed How can I close a .txt file if it is currently opened in the default text viewing application?

I can't just use:

    Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")

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

because this will kill every file that is opened in notepad. I also do not want to have to hardcode Notepad as the application, since this may not be the default file for opening .txt files on the client computer.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Bernoulli Lizard
  • 537
  • 1
  • 12
  • 23
  • Not a good idea to kill another program because it has a text file opened. Play by the rules and inform your user of the problem. Ask him/her to close the other program (And save the content if necessary) – Steve Dec 26 '13 at 16:00
  • I doubt if it's possible in any programming language. You'd need to write function for getting opened file from every existing application. It is possible to check the title of the window of every opened application and then make an action. However killing process is also not a good and convenient idea. – Disa Dec 26 '13 at 16:02
  • If the program is trying to kill the [notepad] process, it will already have warned and have gotten permission from the user to overwrite the existing file, so I don't care if it is opened somewhere. How would I check the title of the window? – Bernoulli Lizard Dec 26 '13 at 16:09
  • @Disa: why would I need to get the opened file for every existing application? Can't I just determine what the default is, and then see if my file is open in THAT application? – Bernoulli Lizard Dec 26 '13 at 17:03

2 Answers2

1

After reading comments I assume that you want to kill notepad.exe process which has opened given text file.

Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")

For Each p As Process In pProcess
    If p.MainWindowTitle.Contains(filename) Then
        p.Kill()
    End If
Next

This code might work for you then

Disa
  • 630
  • 13
  • 42
0

What you are after will not actually work.

This is because you are after text files which are by default set to open in Notepad. And, Notepad doesn't keep a handle to the file. When you open a file in notepad, the entire content of the file is loaded as text and the file handle is closed. (try opening a file in notepad and then deleting it.)

However, if you are after binary files (e.g. Word), then the application uses temp files, and hence you can check, by using the flag FileShare.None

System.IO.File.Open(sFile, FileMode.Open, FileAccess.Read, FileShare.None)

Use this in try-catch to confirm if the file is in use.

Abhitalks
  • 27,721
  • 5
  • 58
  • 81