Click here to Skip to main content
14,668,146 members
Rate this:
Please Sign up or sign in to vote.
See more:

I have a wrote some code to delete a list of files from certain folders on my pc.

I have encountered a small problem where a file is open by another process and it can not be deleted.

Does anyone know of any vb code that would help sort this problem I am having?

Here is my code below:

              Dim F2 As Short = FreeFile()
              For Each foundFile2 As String In My.Computer.FileSystem.GetFiles( _
                  "myfilepath", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
                  FileOpen(F2, foundFile2, OpenMode.Binary, OpenAccess.Read, OpenShare.LockReadWrite)
          Catch ex As Exception
              EnvCode = 101
          End Try

Updated 22-Sep-20 1:44am

Rate this:
Please Sign up or sign in to vote.

Solution 3

Well, that's not easy.
For a file to be deletable, there has to be no open handles to it.
You can either terminate or kill the processes helding those handles, or close the handle itself. Be careful, the other process won't be aware of this. You might crash important applications - but could be better than killing it anyway. Still, that's your concern :)

So, assuming that you can determine which file is locked, you have a complete description here, how to gather all handles, how to filter the file handles and to find the file you are looking for. When you have the handle, you can close it.

It is not VB.NET. You will probably need a lot of P/Invoke, so this might be helpful: NtQuerySystemInformation API Works on 32bit but not on 64bits?[^]
Rate this:
Please Sign up or sign in to vote.

Solution 2

1) You should Try to find the default program(executable) of the file:

Dim key As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
Dim secondKey As String
Dim rtn As String = ""

If Not ext.StartsWith(".") Then
ext = "." & ext
End If

key = key.OpenSubKey(ext)

If key IsNot Nothing Then
secondKey = key.GetValue("").ToString()

If secondKey <> "" Then
key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(secondKey & "ShellOpenCommand")
rtn = key.GetValue("").ToString()
rtn = System.Text.RegularExpressions.Regex.Match(rtn, """(.*?)""").Groups(0).Value
End If
End If

Return rtn
End Function

2) Kill the default process of the file
3) Continue...
CHill60 15-Nov-14 18:35pm
You're a little over a year late with this response

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100