c# wpf -- error when trying to delete an image whose path is the source of a wpf image element

0

I'm using WPF and the language is c#. I have a WPF image element and the source is a binding to a property, as you can see below. When I try to delete the file whose path is that property, it gives error: "file is being used by another process". I can only guess that the reason is because the image element's source is that filepath. And in fact when I take out that Image element, the error does not occur.

Help would be appreciated.

This is my XAML:


<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d" x:Class="test.t"
        Title="Test" 
        MaxHeight="1150"  d:DesignWidth="467.5" d:DesignHeight="357.5" x:Name="TestWindow" >
    <StackPanel>
        <Button Click="Button_Click" Content="do something" />
        <Image Height="300" x:Name="testimage" Source="{Binding Pathtoimage, ElementName=TestWindow}"/>
    </StackPanel>
</Window>


And this is the C# code:

using System.IO;
using System.Windows;

namespace test
{
    public partial class t : Window
    {

        public string Pathtoimage { get; set; } = @"C:\Users\Dean\Desktop\img.jpg";

        public t()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            File.Delete(Pathtoimage);

            /*
            The above line gives following error:

                System.IO.IOException
  HResult=0x80070020
  Message=The process cannot access the file 'C:\Users\Dean\Desktop\img.jpg' because it is being used by another process.
  Source=mscorlib
  StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalDelete(String path, Boolean checkHost)
   at System.IO.File.Delete(String path)
   at test.t.Button_Click(Object sender, RoutedEventArgs e) in A:\Test\Test\MainWindow.xaml.cs:line 18
                */
            MessageBox.Show("success");
        }
    }
}

And of course I tested many different images, at different times, so it isn't as if the file is truly in use.

Thanks in advance.

c#
wpf
asked on Stack Overflow Dec 3, 2020 by celloguy

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0