-2

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

Soubarna Das
  • 57
  • 1
  • 8
  • Have you googled it? have you try anything? Have you searched on SO itself? Duplicate : http://stackoverflow.com/a/11288781/1659563 – Sachin Apr 30 '16 at 05:04
  • I have seen that. But it's not the whole solution for me. It's a part. But I want to check each of the file of a given directory without knowing the name of the files, and if it find any of the open it will show a message of the exception. – Soubarna Das Apr 30 '16 at 08:25

1 Answers1

0

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
            IsFileOpen(file)

        Next

    End Sub

    ' Jeremy Thompson's code from here
    Private Sub IsFileOpen(ByVal file As FileInfo)
        Dim stream As FileStream = Nothing
        Try
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
            stream.Close()
        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
Gabor
  • 3,021
  • 1
  • 11
  • 20