You can use below function to load image without locking it. After loading bitmap you can delete it without any problem.
Usage:
_pic_image.Image = OpenImageWithoutLockingIt("h:\myimage.png")
Function:
Private Function OpenImageWithoutLockingIt(imagePath As String) As Bitmap
If IO.File.Exists(imagePath) = False Then Return Nothing
Using imfTemp As Image = Image.FromFile(imagePath)
Dim MemImage As Bitmap = New Bitmap(imfTemp.Width, imfTemp.Height)
Using g As Graphics = Graphics.FromImage(MemImage)
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.Clear(Color.Transparent)
g.DrawImage(imfTemp, 0, 0, MemImage.Width, MemImage.Height)
Return MemImage
End Using
End Using
End Function
You can also delete read only files by using below function:
Private Function DeleteImageFile(filePath As String, DeleteAlsoReadonlyFile As Boolean) As Boolean
Try
If IO.File.Exists(filePath) = False Then Return True
If DeleteAlsoReadonlyFile Then
Dim fileInf As New FileInfo(filePath)
If fileInf.IsReadOnly Then
'remove readonly attribute, otherwise File.Delete throws access violation exception.
fileInf.IsReadOnly = False
End If
End If
IO.File.Delete(filePath)
Return True
Catch ex As Exception
Return False
End Try
End Function
C# Code:
private Bitmap OpenImageWithoutLockingIt(string imagePath)
{
if (System.IO.File.Exists(imagePath) == false)
return null;
using (Image imfTemp = Image.FromFile(imagePath))
{
Bitmap MemImage = new Bitmap(imfTemp.Width, imfTemp.Height);
using (Graphics g = Graphics.FromImage(MemImage))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(imfTemp, 0, 0, MemImage.Width, MemImage.Height);
return MemImage;
}
}
}
private bool DeleteImageFile(string filePath, bool DeleteAlsoReadonlyFile)
{
try
{
if (System.IO.File.Exists(filePath) == false)
return true;
if (DeleteAlsoReadonlyFile)
{
FileInfo fileInf = new FileInfo(filePath);
if (fileInf.IsReadOnly)
{
//remove readonly attribute, otherwise File.Delete throws access violation exception.
fileInf.IsReadOnly = false;
}
}
System.IO.File.Delete(filePath);
return true;
}
catch (Exception ex)
{
return false;
}
}