In WPF, you may encounter this situation. The image is opened on the interface and cannot be deleted if you want to delete it using File. Delate.
For example:
XAML:
<Window x: Class = "WPF_Testing_Application.Window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "Window1" Height = "300" Width = "300">
<StackPanel Height = "100" Name = "stackPanel1" Width = "200"/>
</Window>
Code:
Public Window1 ()
{
InitializeComponent ();
BitmapImage bi = new BitmapImage ();
Bi. BeginInit ();
Bi. UriSource = new Uri (@ "C: \ Users \ Public \ Pictures \ Sample Pictures \ Autumn Leaves-Copy.jpg ");
Bi. EndInit ();
Image image1 = new Image ();
Image1.Source = bi;
StackPanel1.Children. Add (image1 );
StackPanel1.MouseLeftButtonDown + = delegate {DeleteImage ();};
}
Private void DeleteImage ()
{
StackPanel1.Children. RemoveAt (0 );
File. Delete (@ "C: \ Users \ Public \ Pictures \ Sample Pictures \ Autumn Leaves-Copy.jpg ");
}
In this case, the file is occupied and cannot be deleted.
Solution: www.2cto.com
Change the code:
Public Window1 ()
{
InitializeComponent ();
BitmapImage bi = new BitmapImage ();
Bi. BeginInit ();
Bi. CacheOption = BitmapCacheOption. OnLoad; // Add this line
Bi. UriSource = new Uri (@ "C: \ Users \ Public \ Pictures \ Sample Pictures \ Autumn Leaves-Copy.jpg ");
Bi. EndInit ();
Image image1 = new Image ();
Image1.Source = bi;
StackPanel1.Children. Add (image1 );
StackPanel1.MouseLeftButtonDown + = delegate {DeleteImage ();};
}
You can.
If you use ObservableCollection <BitmapImage> As datasouce,
BitmapImage bmp = new BitmapImage ();
Bmp. BeginInit ();
Bmp. UriSource = new Uri ("Blue hills.jpg", UriKind. Relative );
Bmp. CacheOption = BitmapCacheOption. OnLoad;
Bmp. EndInit ();
You can delete it in the following ways:
BitmapImage img = (BitmapImage) listPictures. SelectedItem;
File. Delete (img. UriSource. ToString ());
From soft2buy