How can I release file / folder locks after using Directory.GetFiles?

I use IO.Directory.GetFiles to search for files in a folder. After the search is completed, I cannot use the files in this folder until my application is closed. I did not find the Dispose function in the DirectoryInfo class, so my question is: how can I free or unlock these files?

My code is:

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

EDIT:

I carefully examined my code (I could not reproduce my problem in another project), and it turned out that this function blocks 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 

This is strange. I close FileStream and delete the whole object, but the file remains locked.

+6
source share
1 answer

You open 2 separate threads, then close only the last one.

  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) 

The first line creates a new filter instance, and then, before it can be used, the second line creates a NEW instance and returns the source text without deleting it.

You will need only one of these lines.

I recommend:

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

Source: https://habr.com/ru/post/969877/


All Articles