dassoubarna dassoubarna - 8 months ago 50
Vb.net Question

Detect if any file in use by other process of a directory in VB

I am trying to get my vb.net application to look inside a folder and then let me know whether any file older is in use by any application. If in use it will show a message box. I am coding in VB.NET 2008, Express Edition. ...Would anybody know how I do that? Thanks


You can extend the suggested solution with enumerating files in a directory.

Imports System.IO
Imports System.Runtime.InteropServices

Module Module1

    Sub Main()

        ' Here you specify the given directory
        Dim rootFolder As DirectoryInfo = New DirectoryInfo("C:\SomeDir")

        ' Then you enumerate all the files within this directory and its subdirectory
        ' See System.IO.SearchOption enum for more info
        For Each file As FileInfo In rootFolder.EnumerateFiles("*.*", SearchOption.AllDirectories)

            ' Here you can call the method from the solution linked in Sachin's comment


    End Sub

    ' Jeremy Thompson's code from here
    Private Sub IsFileOpen(ByVal file As FileInfo)
        Dim stream As FileStream = Nothing
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
        Catch ex As Exception

            If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
                ' do something here, either close the file if you have a handle, show a msgbox, retry  or as a last resort terminate the process - which could cause corruption and lose data
            End If
        End Try
    End Sub

    Private 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

End Module