title: Release handle on file. ImageSource from BitmapImage
body: <p>How can I release the handle on this file?</p>
  
  <p>img is of type System.Windows.Controls.Image</p>
  
  <pre><code>private void Load()
  {
      ImageSource imageSrc = new BitmapImage(new Uri(filePath));
      img.Source = imageSrc;
      //Do Work
      imageSrc = null;
      img.Source = null;
      File.Delete(filePath); // File is being used by another process.
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Solution</strong></p>
  
  <hr>
  
  <pre><code>private void Load()
  {
      ImageSource imageSrc = BitmapFromUri(new Uri(filePath));
      img.Source = imageSrc;
      //Do Work
      imageSrc = null;
      img.Source = null;
      File.Delete(filePath); // File deleted.
  }
  
  
  
  public static ImageSource BitmapFromUri(Uri source)
  {
      var bitmap = new BitmapImage();
      bitmap.BeginInit();
      bitmap.UriSource = source;
      bitmap.CacheOption = BitmapCacheOption.OnLoad;
      bitmap.EndInit();
      return bitmap;
  }
  </code></pre>