Solving C# File Locking Problems During Bitmap Loading
The error message "The process cannot access the file because it is being used by another process" typically arises when a Bitmap object holds a lock on the image file after initialization (e.g., pbAvatar.Image = new Bitmap(filePath)
). This prevents subsequent attempts to access or modify the file.
The solution lies in releasing this lock. A highly effective method involves loading the image directly from a stream, bypassing the Bitmap constructor's file locking mechanism:
<code class="language-csharp">public static Image LoadImageFromStream(string path) { byte[] imageBytes = File.ReadAllBytes(path); using (MemoryStream ms = new MemoryStream(imageBytes)) { Image img = Image.FromStream(ms); return img; } }</code>
This function reads the image file into a byte array, then uses a MemoryStream to load the Image object, avoiding the file lock. This loaded image can then be assigned to your PictureBox (e.g., pbAvatar.Image = LoadImageFromStream(filePath);
).
Performance Considerations
If a Bitmap object is strictly necessary, you can efficiently convert the loaded Image:
<code class="language-csharp">return (Bitmap)Image.FromStream(ms);</code>
Benchmarking reveals that loading directly from the byte array is considerably faster (approximately 0.26 ms per image) than creating a Bitmap from an existing Bitmap (around 0.50 ms per image). This performance gain stems from avoiding an unnecessary image copy.
The above is the detailed content of How to Unlock a File Locked by Bitmap Initialization in C#?. For more information, please follow other related articles on the PHP Chinese website!