2012-04-25 5 views
22

このファイルのハンドルを解除するにはどうすればよいですか?ファイルハンドルを解放します。 BitmapImageのImageSource

IMGは

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. 
} 

型System.Windows.Controls.ImageのMSDNフォーラムで答えを見つけソリューション


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; 
} 
+1

ニースの解決策。あなたは私の日を救った: – gisek

+0

これらの3行は何ですか:img.Source = imageSrc; //作業を行う imageSrc = null; img.Source = null; – MonsterMMORPG

+0

@MonsterMMORPGは心配しないでください... bitmap.CacheOption = BitmapCacheOption.OnLoad;魔法の部分です。 – NitroxDM

答えて

24

です。キャッシングのオプションは BitmapCacheOption.OnLoadとして設定されていない限り

ビットマップストリームが閉じられていません。ですから、このようなものが必要です。

public static ImageSource BitmapFromUri(Uri source) 
{ 
    var bitmap = new BitmapImage(); 
    bitmap.BeginInit(); 
    bitmap.UriSource = source; 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.EndInit(); 
    return bitmap; 
} 

をそして、あなたは上記の方法を使用してImageSourceはを取得するときに、ソースファイル はすぐに閉じられます。

see MSDN social forum

+0

いいですよ。 – NitroxDM

+0

私はこのコードを使用する場合、アプリケーションのメモリ増加の変更はありますか? –

0

私は特に厄介画像上のこのの問題に走り続けました。受け入れられた答えは私にとってはうまくいかなかった。

は代わりに、私は、ビットマップを読み込むためにストリームを使用:

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{ 
    bitmap.BeginInit(); 
    bitmap.StreamSource = fs; 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.EndInit(); 
} 

これは、ファイルハンドルが解放される原因となりました。

関連する問題