如何释放此文件的句柄?
img的类型为System.Windows.Controls.Image
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.
}
Run Code Online (Sandbox Code Playgroud)
解
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;
}
Run Code Online (Sandbox Code Playgroud)
cst*_*ler 30
在MSDN论坛上找到答案.
除非将缓存选项设置为BitmapCacheOption.OnLoad,否则不会关闭位图流.所以你需要这样的东西:
Run Code Online (Sandbox Code Playgroud)public static ImageSource BitmapFromUri(Uri source) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = source; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); return bitmap; }当您使用上述方法获得ImageSource时,源文件将立即关闭.
| 归档时间: |
|
| 查看次数: |
10354 次 |
| 最近记录: |