Load images without locking their files in C#

This example shows how to load images into a C# program without locking their files. When you click the Load Normally button, the program uses the following code to display an image file.

// Load the image normally.
private void btnLoadNormally_Click(object sender, EventArgs e)
{
    if (picSample.Image != null) picSample.Image.Dispose();
    picSample.Image = new Bitmap("essential_algs_75.jpg");
}

This code simply creates a new Bitmap, passing its constructor the name of the file to load. (Visual Studio copies the file into the program’s excutable directory when it builds the program so look for the file there.) If you then try to use Windows Explorer to rename or delete the file, you will fail because the file is locked.

When you click the Load Unlocked button, the program uses the following code to display the image file.

// Load the bitmap without locking it.
private void btnLoadUnlocked_Click(object sender, EventArgs e)
{
    if (picSample.Image != null) picSample.Image.Dispose();
    picSample.Image = LoadBitmapUnlocked("essential_algs_75.jpg");
}

This code calls the following LoadBitmapUnlocked method to load the image file.

// Load a bitmap without locking it.
private Bitmap LoadBitmapUnlocked(string file_name)
{
    using (Bitmap bm = new Bitmap(file_name))
    {
        return new Bitmap(bm);
    }
}

This method loads the image file as usual. It then creates a new Bitmap, passing its constructor the original Bitmap as a parameter. That makes a copy of the original. The using statement disposes of the original Bitmap so the file is no longer locked. Now if you try to rename or delete the file, you will succeed.


Download Example




This entry was posted in files, graphics and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

6 Responses to Load images without locking their files in C#

  1. Pingback: Resize images and save the results in C# |

  2. Pingback: Optimize JPEG compression levels and file sizes in C# |

  3. javad says:

    tankyou very very good

  4. Hamid says:

    That’s Cool !
    Thanks a million.

  5. Feng-Cheng Yang says:

    You excellent work answers my problem right in the point.
    THANKS!!

  6. Pingback: Convert a directory's files to grayscale in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *