Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is the code:
C#
//THIS FUNCTION IS CALLED WHEN I PRESS A BUTTON IN A WINFORM
pictureBox1.Image = Image.FromFile("E:/Projects/01/pics/loading.gif
string cmdCommand = "/C py E:/Projects/01/python/generate_image.py --dim 400"
Process.Start("CMD.exe", cmdCommand);
while (true)
{
  if (File.Exists(path)) //path is a string of where the python script saves the file
  {
    pictureBox1.Image = Image.FromFile(path);
    break;
  }
}

The python script uses pillow to generate a pattern and save it to the same location the variable path is assigned to. And it works but only once, then it stops working.

So i did it manually, i went into the C# application, started it up, generated the first pattern, then started the python script and it says permission denied.

I thought changing the pictureBox image would fix this? How do I dispose or stop using the image in my c# application so python can change it, so i then can load the new image.

What I have tried:

I have tried loading another image from file, but it did not work as I thought.
Posted
Updated 31-Dec-21 1:59am

1 solution

If in doubt, read the documentation: Image.FromFile Method (System.Drawing) | Microsoft Docs[^]
Under "Remarks" it is explicitly stated:
MS Documentation:
The file remains locked until the Image is disposed.

WHat that means is that while the Image exists in your application, an exclusive lock is established on the file that you sourced the images data from - and no other application can open it.

To get round this, you need to read the image, copy it, and Dispose the original:
C#
Image youWanted;
using (Image image = Image.FromFile(file))
    {
    youWanted = new Bitmap(image)
    }
The using block will Dispose the image for you and release the file lock.
 
Share this answer
 
Comments
CodeSie Programming 31-Dec-21 8:50am    
Ah yes ofcourse! Thank you! Didn't even think of the using block.
OriginalGriff 31-Dec-21 9:08am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900