I had a similar problem with displaying images. In a control with an image, I would get a 'File is in use' error whenever the user tried to update the image. The solution was to set the BitmapImage.CacheOption
property to BitmapCacheOption.OnLoad
:
MSDN says Set the CacheOption to BitmapCacheOption.OnLoad if you wish to close a stream used to create the BitmapImage. The default OnDemand cache option retains access to the stream until the image is needed, and cleanup is handled by the garbage collector.
After searching for a similar property that you could use for your MediaElement
, it turns out that there isn't one. However, according to an answer on the chacheoption for mediaelement post from MSDN, there is a (long winded) way to achieve this... from the relevant answer:
I am not sure if your MediaElement is in an UserControl or not. but
whatever the case you can set the UserControl or Control to
IsEnabled=false, which in turn will trigger the Event Handler
IsEnabledChanged. In it place the necessary code to stop the
MediaElement from playback ME.Stop(), then call ME.Clear() and
ME.Source = null. After that you should find no problems to delete the
source file.
ME.Source = new Uri(MediaFilePath);
ME.Play();
...
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
ME.IsEnabled = false; // This will call the Event Handler IsEnabledChanged
System.IO.File.Delete(MediaFilePath);
// Now after the player was stopped and cleared and source set to null, it
// won't object to deleting the file
}
private void ME_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ME.Stop();
ME.Clear();
ME.Source = null;
}
I hope that this helps.