如何释放C# BitmapImage占用的资源?
[csharp] view plain copy
Bitmap是个好东西,但如果是直接Image.FromFile的话,那就会一直锁定该文件,如果你想读取文件后,再马上删除文件,可以这么做
[csharp] view plain copy
Bitmap FileToBitmap(string fileName)
{
// 打开文件
FileStream fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
MemoryStream mstream = null;
try
{
mstream = new MemoryStream(bytes);
return new Bitmap((Image)new Bitmap(stream));
}
catch (ArgumentNullException ex)
{
return null;
}
catch (ArgumentException ex)
{
return null;
}
finally
{
stream.Close();
}
}