[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 File Explorer to rename or delete the file, you will fail because the file is locked. Basically the program keeps the file locked in case it needs to use it to draw the bitmap later.

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.