I’m working on a hobby chess project when I load the piece images it throws an exception that the image cannot be found. I know this is not the case, it has worked before and when I load them in a method it does work. They are located in the right place and the file paths are correct. At first the code used the Bitmap class instead of the Image class, which gave the same result.
My main reason for loading the images in class definition is that I use most images several times and I want to make sure every image is loaded only once.
This shows the class definition and the first button, but an image is loaded for every piece.
public partial class PieceButton : Button
{
private static readonly Image blackBishop = Image.FromFile("images/black_bishop.gif");
Later I will apply the loaded image to the button when a piece moves to it.
The class inherits Button because the default button behaviour is very usefull.
The images are .gif because then the button background remains visible (fields are white or black).
So my question is: How can I load these images properly in the class definition?
Consider adding the images as resources to Resources.resx and have Visual Studio worry about generating the code to actually turn the underlying data into an Image object. This has a number of advantages, the largest being that any issues (like an image not being present) will be caught at compile time because VS generates Properties.Resources.whatever for you ahead of time.
You will also get the “Load Images Once” behavior that you desire