Click here to Skip to main content
15,122,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 2:44am

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?[^]
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900