经常使用PictureBoxPhoto.image = Image.FromFile(pbPath);
此时要删除此图像,往往会报此文件正在被占用的错误!
采取文件流读取方式后解决此问题
/// <summary>
/// 根据图像名称获得图像(从文件流读取,所以原图像可以删除)
/// </summary>
/// <param name="PhotoPath"></param>
/// <returns></returns>
public static Bitmap GetImageFromStream(string PhotoPath)
{
Bitmap bmp = null;
try
{
FileStream fs = new FileStream(PhotoPath, FileMode.OpenOrCreate, FileAccess.Read);
byte[] theData = new byte[fs.Length];
fs.Read(theData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
System.IO.MemoryStream stream = new System.IO.MemoryStream(theData, true);
stream.Write(theData, 0, theData.Length);
bmp = new Bitmap(stream);
}
catch
{
bmp = null;
}
return bmp;
}

本文介绍了如何使用C#从文件流中读取图像,从而避免因PictureBox加载图片导致文件被占用而无法删除的问题。通过创建FileStream,读取文件到byte数组,然后转换为MemoryStream,最后创建Bitmap对象,实现安全获取和删除图像。
最低0.47元/天 解锁文章
328

被折叠的 条评论
为什么被折叠?



