2014-09-24 60 views
0

我認爲我的問題與關閉主題:How can I stop <Image Source="file path"/> process?有關。該主題已關閉,其答案對我無效。在關閉窗口中刪除文件

我的問題是,我無法使用File.Delete(路徑)。它提供了例外情況:「其他信息:該進程無法訪問文件'C:\ Images \ 2014_09 \ auto_12_53_55_beszelri_modified.jpg',因爲它正在被另一個進程使用」。

我想在Window_OnClosed事件中調用這個方法。這個想法是,當我關閉窗口時,我必須刪除圖像的jpg文件。此文件的路徑是WPF中圖像控件的來源。我試圖在調用該方法之前將Image源設置爲null,但它不起作用。如何在關閉窗口之後或過程中刪除該文件。當我嘗試關閉那個地方的其他文件時,它是成功的。

這是關閉事件的代碼。 CreateFileString方法創建路徑。

private void ImageWindow_OnClosed(object sender, EventArgs e) 
{ 
    var c = CarImage.Source.ToString(); 
    var a = CreateFileString(c); 
    CarImage.Source = null; 

    File.Delete(a); 
} 
+0

有'Image'被顯示在用戶界面? – Sheridan 2014-09-24 13:35:05

+0

我在XAML中創建圖像。我在OnLoaded事件中設置它的來源。圖像顯示在窗口中,我可以對其進行操作(繪製一些圖形)。 – darson1991 2014-09-24 13:37:52

+0

檢查這些[答案](http://stackoverflow.com/questions/1811101/wpf-application-freeing-resources-images) – 2014-09-24 13:37:59

回答

1

出於一些煩人的原因,WPF中的標記解析器會打開圖像並將連接保留爲打開的物理文件。我有一個類似的問題,允許用戶切換圖像。我得到的方式是使用IValueConverter加載Image並將BitmapImage.CacheOption設置爲BitmapCacheOption.OnLoad。試試這個:

public class FilePathToImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value.GetType() != typeof(string) || targetType != typeof(ImageSource)) return false; 
     string filePath = value as string; 
     if (filePath.IsNullOrEmpty() || !File.Exists(filePath)) return DependencyProperty.UnsetValue; 
     BitmapImage image = new BitmapImage(); 
     try 
     { 
      using (FileStream stream = File.OpenRead(filePath)) 
      { 
       image.BeginInit(); 
       image.StreamSource = stream; 
       image.CacheOption = BitmapCacheOption.OnLoad; 
       image.EndInit(); 
      } 
     } 
     catch { return DependencyProperty.UnsetValue; } 
     return image; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return DependencyProperty.UnsetValue; 
    } 
} 

您可以使用它像這樣:

<Application.Resources> 
    <Converters:FilePathToImageConverter x:Key="FilePathToImageConverter" /> 
</Application.Resources> 

...

<Image Source="{Binding SomeObject.SomeImageFilePath, 
    Converter={StaticResource FilePathToImageConverter}, Mode=OneWay}" />