user1709660
user1709660

Reputation: 1

I Can't delete folders in %Temp%

I create new folders in %Temp%. They are empty and in use nowhere. I delete temps files using these vb.net codes.

For Each filepath In Directory.GetFiles(TempFolderPath)
            Try
                File.Delete(filepath)
                Directory.Delete(filepath)
            Catch ex As Exception
                MessageBox.Show(ex.ToString)

            End Try
Next

What's wrong?

Upvotes: 0

Views: 191

Answers (1)

WozzeC
WozzeC

Reputation: 2660

What you are doing wrong is that you are trying to delete a folder using the path to a file. This will not work.

This works for me. This deletes all files and all folders inside the folder you specify. It will run recursively which means all files and folders will be gone. If you want to delete the folder you supply (in this case %Temp%) then uncommen the commented line and remove the "directory.Delete(subfolder)" line.

Private Sub RemoveFilesAndFoldersRecursively(ByVal Folder As String)
        For Each Subfolder As String In IO.Directory.GetDirectories(Folder)
            RemoveFilesAndFoldersRecursively(Subfolder)
            IO.Directory.Delete(Subfolder)
        Next
        For Each file As String In IO.Directory.GetFiles(Folder)
            IO.File.Delete(file)
        Next
        'IO.Directory.Delete(Folder)
    End Sub

Upvotes: 2

Related Questions