2

I use this code to populate WPF Image Control.

string pathToImage = System.IO.Path.Combine(Settings.ContentFolderPath, file);

Image image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.EndInit();
double ratio = src.Width / src.Height;
image.Source = src;
image.Stretch = Stretch.Uniform;
image.Height = marquee1.Height;
image.Width = marquee1.Height * ratio;
lstItems.Items.Add(image);

Also I have some parallel Task to update this image file.

But when I try to delete it I am getting the error: File is busy by other process you cannot delete this file.

How to resolve this issue?

Thank you!


UPDATES

So thank you all of you!

The final solution needs to implement

src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;

the working code looks like

Image image = new Image();

BitmapImage src = new BitmapImage();
src.BeginInit();
src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.EndInit();
double ratio = src.Width / src.Height;

image.Source = src;
image.Stretch = Stretch.Uniform;
image.Height = marquee1.Height;
image.Width = marquee1.Height * ratio;
lstItems.Items.Add(image);
result = image.Width;

3 Answers 3

4

MSND BitmapImage.CacheOption says:

Set the CacheOption to BitmapCacheOption.OnLoad if you wish to close a stream used to create the BitmapImage.

Set the BitmapImage.CacheOption to OnLoad:

BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(pathToImage, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
Sign up to request clarification or add additional context in comments.

Comments

1

Set the CacheOption property of the BitmapImage to BitmapCacheOption.OnLoad. This will cause it to load the image into memory and close the original file, which should allow you to delete it.

Comments

0

Also I have some parallel Task to update this image file ... when I try to delete it I am getting the error

In general, you can't delete a Windows file while a process is using it. The consumer Windows FAQs include this page to describe this restriction. And as MSDN describes, File.Delete will refuse to delete a file that's in use.

1 Comment

Just as a note, you could open a file with FILE_SHARE_DELETE/FileShare.Delete and be able to use File.Delete() on it, but WPF does not use that mode when opening images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.