Can't delete a file displayed in ListView ("File in use") even after removing it from window.

I have a ListView displaying a collection of icons. The user can then select different icons (checkboxes) to do things like Copy or Delete.
Problem is, when I try to delete the actual file from the disk, I get an error telling me the file is "in use" ("vshost.exe", the VS runtime during testing).
I thought maybe it was because it still appeared in the window and was still in the ImageList, but even after removing it from both locations, I still get the error. My code:
Dim intCnt As Integer = 0
Do
ImageList2.Images.RemoveAt(intIconsChecked(intCnt)) ' Remove from collection.
lsvCollection.Items.RemoveAt(intIconsChecked(intCnt)) ' Remove from ListView window.
FileIO.FileSystem.DeleteFile(strIconPath & "\Icon" & Format(intCnt + 1, "00") & ".rsc") ' "+1" b/c Icons start with "01".
FileIO.FileSystem.DeleteFile(strIconPath & "\Icon" & Format(intCnt + 1, "00") & ".png") ' "In use" Error here.
".rsc" deletes just fine, so I know I'm deleting the correct file. Why does VS still think the file is still "in use"?
Thx

Mugsy,
Consider this as food for thought, even if you don't use it.
If you set it up right then you can control how it works. A reference is a reference and any left behind will cause you grief down the road when you try to delete things.
As an example, a simple class follows. It does *not* implement IDispose, although it does have a private shared Dispose method in it:
Public Class MyImages
Private _bmp As Bitmap
Private _name As String
Private _sourceFilePath As String
Private Sub New(ByVal bmp As Bitmap, _
ByVal name As String, _
ByVal filePath As String)
_bmp = bmp
_sourceFilePath = filePath.Trim
_name = name.Trim
End Sub
Public ReadOnly Property Bmp As Bitmap
Get
Return _bmp
End Get
End Property
Public ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public ReadOnly Property SourceFilePath As String
Get
Return _sourceFilePath
End Get
End Property
Public Shared Sub AddNew(ByRef miList As List(Of MyImages), _
ByVal imageFilePath As String)
Try
If miList Is Nothing Then
Throw New ArgumentNullException("The collection of MyImages cannot be null.")
ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
Throw New ArgumentException("The file path of the image cannot be null or empty.")
ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
Throw New IO.FileNotFoundException("The file path of the image could not be located.")
Else
' Should do validation here that the file
' is actually an image but I'll not do this
' here...
Dim thisBMP As Bitmap = New Bitmap(imageFilePath)
miList.Add(New MyImages(thisBMP, GetFileNameWithoutExtension(imageFilePath), imageFilePath))
End If
Catch ex As Exception
Throw
End Try
End Sub
Public Shared Sub AddNew(ByRef miList As List(Of MyImages), _
ByVal imageFilePath As String, _
ByVal imageName As String)
Try
If miList Is Nothing Then
Throw New ArgumentNullException("The collection of MyImages cannot be null.")
ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
Throw New ArgumentException("The file path of the image cannot be null or empty.")
ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
Throw New IO.FileNotFoundException("The file path of the image could not be located.")
ElseIf String.IsNullOrEmpty(imageName) OrElse imageName.Trim = "" Then
Throw New ArgumentException("The name of this image cannot be null or empty.")
Else
' Should do validation here that the file
' is actually an image but I'll not do this
' here...
Dim thisBMP As Bitmap = New Bitmap(imageFilePath)
miList.Add(New MyImages(thisBMP, imageName, imageFilePath))
End If
Catch ex As Exception
Throw
End Try
End Sub
Public Shared Sub Remove(ByRef miList As List(Of MyImages), _
ByVal imageFilePath As String, _
Optional ByVal removeFilePathAlso As Boolean = False)
Try
If miList Is Nothing Then
Throw New ArgumentNullException("The collection of MyImages cannot be null.")
ElseIf String.IsNullOrEmpty(imageFilePath) OrElse imageFilePath.Trim = "" Then
Throw New ArgumentException("The file path of the image cannot be null or empty.")
ElseIf Not My.Computer.FileSystem.FileExists(imageFilePath) Then
Throw New IO.FileNotFoundException("The file path of the image could not be located.")
Else
Dim findInstance As System.Collections.Generic.IEnumerable(Of MyImages) = _
From mi As MyImages In miList _
Where mi.SourceFilePath = imageFilePath
If findInstance.Count <> 1 Then
Throw New ArgumentException("The instance of MyImages specified by the" & vbCrLf & _
"image file path is not in the collection.")
Else
Dispose(findInstance.First)
If removeFilePathAlso Then
My.Computer.FileSystem.DeleteFile(findInstance.First.SourceFilePath)
End If
miList.Remove(findInstance.First)
End If
End If
Catch ex As Exception
Throw
End Try
End Sub
Private Shared Sub Dispose(ByVal instance As MyImages)
If instance IsNot Nothing AndAlso instance._bmp IsNot Nothing Then
instance._bmp.Dispose()
instance._bmp = Nothing
End If
End Sub
End Class
When you look through that, look specifically at the "Remove" method and in particular, look at the order in which things are done. That's the critical part in this.
I tested it with a simple form:
Two buttons, a checkbox, and a picturebox. I also copied a small folder full of image files to my desktop since I'll be deleting a file from it. Following is the code for Form1:
Option Strict On
Option Explicit On
Option Infer Off
Imports System.IO.Path
Public Class Form1
Private miList As New List(Of MyImages)
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim desktop As String = _
My.Computer.FileSystem.SpecialDirectories.Desktop
Dim imgFolder As String = _
Combine(desktop, "Images")
PictureBox1.BorderStyle = BorderStyle.FixedSingle
For Each imgFilePath As String In My.Computer.FileSystem.GetFiles(imgFolder)
MyImages.AddNew(miList, imgFilePath)
Next
btn_RemoveFirstImage.Enabled = False
CheckBox_RemoveSourcePath.Enabled = False
End Sub
Private Sub btn_ShowFirstImage_Click(sender As System.Object, _
e As System.EventArgs) _
Handles btn_ShowFirstImage.Click
Try
If miList.Count >= 1 Then
With PictureBox1
.SizeMode = PictureBoxSizeMode.Zoom
.Image = miList(0).Bmp
End With
btn_RemoveFirstImage.Enabled = True
CheckBox_RemoveSourcePath.Enabled = True
End If
Catch ex As Exception
MessageBox.Show(String.Format("An exception was thrown:{0}{0}{1}", vbCrLf, ex.Message), _
"Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Private Sub btn_RemoveFirstImage_Click(sender As System.Object, _
e As System.EventArgs) _
Handles btn_RemoveFirstImage.Click
Try
If miList.Count >= 1 Then
MyImages.Remove(miList, miList(0).SourceFilePath, CheckBox_RemoveSourcePath.Checked)
End If
PictureBox1.Image = Nothing
btn_RemoveFirstImage.Enabled = True
CheckBox_RemoveSourcePath.Enabled = True
Catch ex As Exception
MessageBox.Show(String.Format("An exception was thrown:{0}{0}{1}", vbCrLf, ex.Message), _
"Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
End Class
Running it is straightforward:
Now when I click to show the first one:
A different image is shown because that first one no longer exists - either in the collection or in the folder.
Closing/disposing all references is the key and the order matters.
Something to consider the next time around. :)
Still lost in code, just at a little higher level.

Similar Messages

  • How can I delete a page in a pdf file I received?

    How can I delete a page in a pdf file that I received? I only have Adobe Reader X.

    Thanks very much for your help.  I’ll look into Acrobat.  Have a great week.
    Stephen E. Hincks, Sr.
    (cell) 301.346.6110

  • I want to clean up my icloud account but I can not delete my mail storage and I don't using icould for my mails?

    I want to clean up my icloud account but I can not delete my mail storage and I don't using icould for my mails so there's nothing in the trash.

    Which email provider do you use if not iClouf?

  • HT4059 Have several books that were purchased recently, when all the sudden they have multiplied having 20 or more copies in my library   How can I delete them because it won't let me use the edit tab?

    Have several books that were recently purchased. This week these books have multiplied into at least 20 or more copies within my library. How can I delete them because it will not let me use the edit tab?

    Do they have the cloud icon on them ? When I had Settings > iBooks > Show All Purchases 'on' I was getting multiple copies of books that were only in the cloud showing on the bookshelf in the app - turning that setting 'off' stopped them showing (you can see what books are available for redownloading, and redownload them, via the Purchased tab in the ibookstore in the app)

  • I can't delete or alter songs, movies, etc, on my iPod (running on iOS 6)  from my MacBook, even though I synced the two last year.  Any advice?

    I can't delete or alter songs, movies, etc, on my iPod (running on iOS 6)  from my MacBook, even though I synced the two last year.  Any advice?

    If the photos were synced to the iPod you have to unsync them. Unsyncing is also covered here
    Sync photos to your iPhone, iPad, and iPod touch in iTunes - Apple Support

  • How can I burn just a few photos to a cd using Photoshop Elements 11 on a windows 7 computer?

    As a fairly new user of Photoshop Elements 11 I would like to burn just a few photos to a cd, not he whole catalogue. Please can somebody suggest an answer to this problem.

    Thanks for your help, much appreciated.
    Original message----
    From : [email protected]
    Date : 15/09/2014 - 14:21 (GMTST)
    To : [email protected]
    Subject :  How can I burn just a few photos to a cd using Photoshop Elements 11 on a windows 7 computer?
        How can I burn just a few photos to a cd using Photoshop Elements 11 on a windows 7 computer?
        created by 99jon in Photoshop Elements - View the full discussion
    File >> Export As New
    Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at https://forums.adobe.com/message/6730807#6730807
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page:
    To unsubscribe from this thread, please visit the message page at . In the Actions box on the right, click the Stop Email Notifications link.
    Start a new discussion in Photoshop Elements by email or at Adobe Community
    For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • I bought the student and teacher version of CS5 extended for windows. Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?

    i bought the student and teacher version of CS5 extended for windows. Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?

    Can I download the Mac version to my new  apple computer  and use the same serial number after removing phtoshop from my PC?
    Short answer: not for CS5.
    Platform swaps are available but only for CS6
    Order product | Platform, language swap

  • I cannot log in my account but can as a guest even after removing the password

    i cannot log in my account but can as a guest even after removing the password

    Hi Kabiru,
    Thanks for visiting Apple Support Communities.
    You may want to use the steps in this article to reset your user account password:
    OS X: Changing or resetting an account password
    http://support.apple.com/kb/HT1274
    Best,
    Jeremy

  • Can you still get your iPhone repaired on warranty at apple even if you bought from carphone warehouse ?

    My iPhone 5 lock button is broke can I take it to apple to get fixed on warranty even though it's from carphone warehouse ?

    Apple handles all iPhone warranty/support in the UK. Be aware, Apple does not fix iPhones in the UK, they replace them. So, before you go to an Apple store, backup your phone. If covered by warranty, the phone will be replaced for free. If not under warranty, the cost will be US $229.

  • I need help removing CS3 from Windows 7 so I can reinstall

    I need help removing CS3 from Windows 7 so I can reinstall

    Before trying to remove try re-installing CS3 right on top of the current install.  Often re-installing Photoshop on top of itself fixes the install.  If it does be sure to apply the cs3 updates.
    Download Adobe CS4 and CS3 Free Trials Here (incl. After Effects) | ProDesignTools
    your product key can be retrieved from here https://www.adobe.com/account/my-products-services.html
    use these links for the updates.
    Adobe - Photoshop : For Macintosh
    Adobe - Photoshop : For Windows

  • HT2905 I can't find the option "Display duplicates" under File

    I'm trying to clean my itunes library and remove all the duplicate items. I read the article How to find and remove duplicate items in your iTunes library and it tells to click on File>Display Duplicates, but I don't have that option under my File. What should I do?

    Use Shift > View > Show Exact Duplicate Items to reveal the exact duplicates as this is normally a more useful selection. You need to manually select all but one of each repeating group to remove. If the duplicates were added recently sorting on date added and deleting the recent additions can be straightforward, although you'll want to make sure there really two sets of files with the same content before you throw any away otherwise you may find your remaining tracks have been broken by the clean-up process.
    Use my DeDuper script if you don't want to do it by hand. Please take note of the warning to backup your library before deduping. See this thread for background.
    tt2

  • HT1923 I can't delete the Apple folder in Common Files

    My computer would not recognize my iPhone.  I tried the troubleshooting tips found online, uninstalling everything in order.  When verifying all files had been removed, I could not delete the Apple folder in Common Files as it says the folder or a file in it is open in another program.  When checking my programs I see iCloud remains (published by Apple).  Need that be uninstalled as well?  How important is it to delete the Apple folder which has an Internet Services folder in which are two other folders (filled with files), an application AppleOutloodDAVConfig64, and three application extensions?  I can no longer remember if my phone had remained connected to the computer throughout all of the process or not,

    Does it say something is in use in there?

  • Can I delete one the 2 exact same files in Finder, without deleting the other one Automatically too?

    I have backed up and have removed a User account. since then, I have 1 user account, but all files are duplicate. Instead of having 199GB on my disk, i now have about the double. Ifound some stuff to delete, but there are also apple apps that are double. Can i delete half of them, so that only one copie stays and not both delete?
    Thanks for helping out.

    no obviously not. it's not in the trash if you are worried copy the second copy and change the name to something else. then delete both and after deleting both rename the copy the same as the original.

  • How can I delete over 1,000,000 tiny files?

    On the MacBook forum they ran out of ideas and suggested I post this here.
    I need to delete 1 million files off my XP volume stuck in my Mac Trash Bin.
    Windows won't even LOAD the directory to do it in small chunks, and OSX tries to COUNT all the files while "preparing" to delete.
    Here is the other thread.
    http://discussions.apple.com/thread.jspa?messageID=12538756#12538756

    Well, XP doesn't support 2TB drives, limitation of MBR.
    I've found Windows 7 to be solid and rare to have any issue, and able to handle concurrent deleting and emptying the trash.
    NTFS does not like Mac HFS file names with special characters.
    I tend to agree though with wiping XP. And I'd say Mac OS has more trouble then Windows 7 with what you are trying to do.
    What was that folder and what type of contents? you say a lot of small files, such as all those hidden folders from Mac?
    Why would you try to empty the trash from the other platform? sounds like it would have to be FAT partition and maybe it is FAT/MSDOS that gets stuck, though with your hard drive I'd also guess purely it is NTFS, and the only way for Mac OS to write to (and empty) trash is you use a NTFS 3rd party driver.
    And why backups for any platform are a must.

  • How do I delete a file that says it's in use even though it isn't??!

    Hi! I'm hoping someone can help me please! I'm being driven insane by a file on my Mac that I can't delete. It is a temp Illustrator file which created itself out os some tenuous necessity that I don't comprehend! When I try to send it to the trash a message comes up saying '+The operation can’t be completed because the item “AI Temp 0003560350” is in use+' even though it isn't! I have tried closing Illustrator to make doubly sure it isn't in use but it hasn't worked. I don't suppose it's very important to delete it but it's really bugging me!
    Any advice much appreciated!
    Thanks!

    katie-cutie wrote:
    I'm being driven insane by a file on my Mac that I can't delete.
    have you tried restarting your Mac ?
    also, see this article on how to resolve _*Trash Problems*_.
    JGG

Maybe you are looking for