JackSparrow
JackSparrow

Reputation: 389

Checking if a specific files is currently open

I was wondering if it was possible to check if the file "test.txt" is open? and if so then display a message that the file is in use? My biggest problem is that the file can be opened in notepad, word, excel etc. I have some basic coding, which checks if the file is open - what I am trying to do is check if the file is currently open and if its not in use then proceed with the coding, I have the following coding so far.

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

For Each p As Process In Process
    If p.MainWindowTitle.Contains("test") Then
        MessageBox.Show("file open")
    Else
        'Run my code
    End If
Next

For Each p2 As Process In Process2
    If p2.MainWindowTitle.Contains("test") Then
        MessageBox.Show("file open")
    Else
        'Run my code
    End If
Next

Upvotes: 1

Views: 752

Answers (2)

Jeremy Thompson
Jeremy Thompson

Reputation: 65692

Why dont you try performing an operation on the file (eg open as suggested by @ChrisW) and check if its locked instead:

eg

Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
' do something? 
End If
End Try

Private Shared Function IsFileLocked(exception As Exception) As Boolean
    Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
    Return errorCode = 32 OrElse errorCode = 33
End Function

Upvotes: 1

mike
mike

Reputation: 172

Many applications create temporary copies of a file when they load them. So it is difficult to check this. You could create a debugger to see which file is loaded by a binary which may be overkill.

Or use something like this:

try
{
  stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
}
catch (IOException)
{
  // the file is locked and not available to read or write.
  return true
}
finally
{
 // close the stream
}

Upvotes: 0

Related Questions