I am writing a WinForm application using VS2010 & VS2012 with .Net4.
In the application I load individual images into pictureboxes and then delete those images the user does not wish to keep.
Every time I try to delete these "unwanted" images I get the above error message:
"The process cannot access the file xxxxxx because it is being used by another process"
The following is used to load an image into a dynamically created picturebox together with the code to delete the unwanted images.
Option 1:
Load Image:
picBox.Image = Image.FromFile(imgInfo.FullName).GetThumbnailImage(128, 128, Nothing, Nothing)
Delete Image:
For Each imgFile As String In Directory.GetFiles(imgSharedFolder)
File.Delete(imgFile)
Next imgFile
Option 2:
Since loading an image file into a picturebox will "lock" the image file I tried the following by reading the image file into a FileStream and then Close the FileStream after loading the image into the picturebox
Load:
fs = New System.IO.FileStream(imgInfo.FullName, IO.FileMode.Open, IO.FileAccess.Read)
picBox.Image = System.Drawing.Image.FromStream(fs).GetThumbnailImage(128, 128, Nothing, Nothing)
fs.Close()
Delete:
Dim picList As String() = Directory.GetFiles(imgSharedFolder, "*.jpg")
For Each f As String In picList
File.Delete(f)
Next f
I get the same error message.
Option 3:
After some more searching, reading and trying I came across this suggestion to create an image object and then Dispose of the image object once the image is loaded into the picturebox:
Load:
Dim newImage As Image
newImage = Image.FromFile(imgInfo.FullName).GetThumbnailImage(128, 128, Nothing, Nothing)
picBox.Image = newImage
Unfortunately I just got the same error message.
Is there any other possible solution to this problem, something I may have overlooked ?