I am describing my work process bellow:
I get image files from a directory.
Creating a
PictureBox
array for displaying the images.Creating a
Image
array from the files that I got from the directory. I am creating this array for making the image source ofPictureBox
.I am copying the files to another directory. By this:
File.Copy(allFiles[i],fullPath+fullName+"-AA"+nameString+ext);
Now I want to delete the files from the directory. For this I am doing this:
File.Delete(allFiles[i]);
But its giving me this error:
The process cannot access the file 'C:\G\a.jpg' because it is being used by another process.
Please tell me how to resolve this? I didn't attach the full code here because it'll be large. Please ask me if you want to see any part of my code.
Of course it's being used.
Copy the files to another directory first (Step 4),
Delete the old directory
then do the third step (assigning it to a array and loading it to PictureBox) from the newly copied directory.
Alternative:
You must close the stream handler before deleting the files..
Chances are you are loading the image directly from the file. For example,
If you look up the documentation for the
Image.FromFile
method, you will find that it actually locks the file until theImage
is disposed. (In fact, most other loading methods in theImage
class also locks the file until theImage
is disposed.)So to work around this problem, copy the picture file contents to memory and load it from there. For example,
That way, the file itself will remain unlocked and you can freely move/delete it.