Delete a file being used by another process
Another way is to delete file. Load your file using FileStream class and release an file through stream.Dispose(); it will never give you the Exception "The process cannot access the file '' because it is being used by another process."
using (FileStream stream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = Image.FromStream(stream);
stream.Dispose();
}
// delete your file.
File.Delete(delpath);
In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad
flag. One way to do this would be this:
string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();
Although setting BitmapCacheOption.OnLoad
works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource
property instead of UriSource
:
string filename = ...
BitmapImage image = new BitmapImage();
using (var stream = File.OpenRead(filename))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
it may be Garbage Collection issue.
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(picturePath);