Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top