I am writing a program to manipulate image file names. I load the image using IO.FileStream and close the filestream after loading the image into the image box, but if I try to now rename the original file I frequently get file locked error. Nothing else is using this image.
This is how I load the image Dim fs = New System.IO.FileStream("Original File Name", FileMode.Open, FileAccess.Read) imgImage.Image = Image.FromStream(fs) fs.Close()
This is the code I am using to try and rename the file My.Computer.FileSystem.RenameFile("Original File Name", "New File Name")
Why does this only work sometimes, more often than not it throughs up the exception? Any suggestions for how to do this?
As I understand it FileStream having been opened and closed should not put a lock on the file at all.
I have put in code to see if the file is open and it does show the file is open but I cannot see what left it open or how to close it.
Try
Dim myStream As IO.FileStream
myStream = IO.File.Open("Original file name", IO.FileMode.Open, IO.FileAccess.Read)
myStream.Close()
Debug.Print("File was not locked")
Catch Ex As Exception
Debug.Print("File was locked")
End Try