-3

My VB.NET junk cleaner cannot delete aria-Debug-10144.log since it is used by another process.

I tried this:

Imports System.Collections.ObjectModel
Imports System.IO

Public Class Form1
    Dim TempDirs As ReadOnlyCollection(Of String)
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TempDirs = (My.Computer.FileSystem.GetDirectories("C:\Users\Aitor\AppData\Local\Temp"))
        Dim ListDirs As List(Of String) = TempDirs.ToList
        Dim directoryName As String = "C:\Users\Aitor\AppData\Local\Temp"
        For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
            If Not deleteFile.ToString = "aria-Debug-10144.log" Then
                File.Delete(deleteFile)
            End If
        Next
        MsgBox("Clean completed!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Results")
    End Sub
End Class

But it still tries to do it.

Can anybody help me?

  • Also sorry if the code is very bad :( – Rubiktor012 Dec 31 '19 at 13:35
  • 1
    I suggest you, at least, use the registered `TEMP` and `TMP` (User and Machine) Environment Variables to read the current Temp paths. Include `[drive]:\Windows\Temp` if not already in the list (e.g., `Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)` (also `TMP`) `Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine))` (also `TMP`). Then, since a file may be locked or unavailable because of lack of access privileges, Try/Catch `IOException` and `UnauthorizedAccessException`. There are **many** other temporary storage directories in a system. – Jimi Dec 31 '19 at 13:54
  • You may want to log the file you couldn't remove, so you can further investigate why the process failed for some of them (using tools that analyze the file system). See also [Is there a way to check if a file is in use?](https://stackoverflow.com/q/876473/7444103) and the duplicate [How to check for file lock?](https://stackoverflow.com/q/1304/7444103) for some more info. – Jimi Dec 31 '19 at 14:02
  • Directory.GetFiles returns the full filenames (including the path) so, when your check against the filename without a path the condition is never met and you try to delete the file you want to exclude. I think that you need to use the debugger (or learn how to use it) because these "little" problems are solved immediately looking at your code through a debugger [Tutorial Debug C# code using Visual Studio](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2019) – Steve Dec 31 '19 at 14:12
  • 2
    Use [Path.GetFileName(deleteFile)](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.8). This is not a great idea, at least look at the FileInfo.LastAccessTime so you don't screw up too many running programs. Fwiw, Win10 already cleans this directory up automatically. – Hans Passant Dec 31 '19 at 14:18

1 Answers1

0

There are two reasons:

Firstly, the selected file is being occupied by another program. In this case, you need to determine whether the selected file is occupied before deleting it. Here is a small example.

Imports System.Runtime.InteropServices

Public Class Form1
    <DllImport("kernel32.dll")>
    Public Shared Function _lopen(ByVal lpPathName As String, ByVal iReadWrite As Integer) As IntPtr

    End Function
    <DllImport("kernel32.dll")>
    Public Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean

    End Function

    Public Const OF_READWRITE As Integer = 2
    Public Const OF_SHARE_DENY_NONE As Integer = &H40
    Public Shared ReadOnly HFILE_ERROR As IntPtr = New IntPtr(-1)

    Public Shared Function IsFileOccupied(ByVal filePath As String) As Boolean
        Dim vHandle As IntPtr = _lopen(filePath, OF_READWRITE Or OF_SHARE_DENY_NONE)
        CloseHandle(vHandle)
        Return If(vHandle = HFILE_ERROR, True, False)
    End Function


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        If (IsFileOccupied("C:\Users\juliex\AppData\Local\Temp\aria-debug-13836.log")) Then
            MessageBox.Show("File is already occupied")
        Else
            MessageBox.Show("File is not occupied")
            'Then do some delete operation.
        End If
    End Sub
End Class

Secondly, the selected file is a temporary file and is currently locked. If you want to clear the temporary files it owns, you need to have full control to unlock these files and then delete them! You should be very careful if you want to delete the TEMP file, whether it is owned by the application or by another owner. The original application may have applied the lock because it wanted to use the file! At this time you can refer to this link below:

1.How can I unlock a file that is locked by a process in .NET

2.https://social.msdn.microsoft.com/Forums/vstudio/en-US/9e2044c5-ae5d-4552-a335-01cc567dfc58/how-to-unlock-a-file-used-by-other-process?forum=csharpgeneral

Julie Xu-MSFT
  • 334
  • 1
  • 5