检测VB中目录的其他进程是否正在使用任何文件

时间:2016-04-30 05:02:13

标签: vb.net

我正在尝试让我的vb.net应用程序查看文件夹,然后让我知道任何应用程序是否正在使用任何较旧的文件。如果在使用中它将显示一个消息框。我在VB.NET 2008,Express Edition中编码。 ......有人知道我是怎么做到的吗?感谢

1 个答案:

答案 0 :(得分:0)

您可以通过枚举目录中的文件来扩展建议的解决方案。

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
相关问题