6

I'm using IO.Directory.GetFiles to search for files in a folder. After the searching is done, I can't use files in this folder until my application is closed. I haven't found any Dispose functions in DirectoryInfo class, so my question is: How can I release or unlock these files?

My code:

Dim list = IO.Directory.GetFiles(folder, "*.*", IO.SearchOption.AllDirectories)

EDIT:

I have examined my code once again very carefully (I couldn't reproduce my problem in another project) and it turned out that this function is locking the files:

   Public Function ComputeFileHash(ByVal filePath As String)
        Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
        Dim f As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
        f = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
        md5.ComputeHash(f)
        f.Close()
        f.Dispose()
        Dim hash As Byte() = md5.Hash
        Dim buff As Text.StringBuilder = New Text.StringBuilder
        Dim hashByte As Byte
        For Each hashByte In hash
            buff.Append(String.Format("{0:X2}", hashByte))
        Next
        Dim md5string As String
        md5string = buff.ToString()
        Return md5string
    End Function

It's strange. I'm closing the FileStream and disposing the whole object but file remains locked.

4

1 回答 1

9

您正在打开 2 个单独的流,然后只关闭最后一个。

 Dim f As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
 f = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)

第一行创建一个新的文件流实例,然后,在它可以使用之前,第二行创建一个新实例并丢弃原始实例而不丢弃它。

您应该只需要这些行之一。

我建议:

Dim f As New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
于 2014-05-26T21:12:48.073 回答