I need to move/rename some images which are loaded inside of pictureboxes, the images are stored in a folder in the executable path of the application. Before I can move/rename any image I have to make sure it is not in use, so I tried to load another image from the executable path of the application into this picturebox and also tried to "null" the picturebox image property.
If I want to move on in my program the image is still locked I verifyed this by using the following code:
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
I also tried to use the code from here: What process locks a file?
Which returned me the following: System.Collections.Generic.List´1[System.Diagnostics.Process]
I have to tell you that I am also fighting with an AccessViolationException using the same images and methods. I am not entirely sure if it is the same problem...is the way I saved the Images wrong or the way I am using them? Let me know if you need more code or Information!
EDIT:
Both the link from TaW and the answer from Anon Coward did not work for me and I really tried my hardest to make it work, I tried to dispose and null the picturebox, the image etc. .I found a solution mixed with your Suggestion but it is a very dirty one...
var image2 = Image.FromFile(infos[i].FullName);
MemoryStream ms = new MemoryStream();
if (ImageFormat.Jpeg.Equals(image2.RawFormat))
{
// JPEG
image2.Save(ms, ImageFormat.Jpeg);
}
else if (ImageFormat.Png.Equals(image2.RawFormat))
{
// PNG
image2.Save(ms, ImageFormat.Png);
}
else if (ImageFormat.Gif.Equals(image2.RawFormat))
{
// Bitmap
image2.Save(ms, ImageFormat.Bmp);
}
else if (ImageFormat.Icon.Equals(image2.RawFormat))
{
// Icon
image2.Save(ms, ImageFormat.Icon);
}
image2.Dispose();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(infos[i].FullName);
Image newImg = Image.FromStream(ms);
newImg.Save(neuer_name2);
newImg = null;
I know that using GarbageCollection is not the right way, but I have no idea what blocks the images...so I am still searching for a real solution here.