Search code examples
c#pathpicturebox

I have a problem with a photo path for array


So Im working on a project in c# which is a space shooting game. Anyways Im trying to put the bullets on an array and so far so good but when I run the game and I shoot, instead of bullets it spawns squares with x in the middle(error). Can anyone help me with that? Here's the part of the code:

private void shotfired(int firX)
        {
            PictureBox shot = new PictureBox();
            shot.ImageLocation = "bullet.png"; ***<-This is the photo i try to use***
            shot.Location = new Point(firX+50 , Player.Location.Y - 20);
            shot.Size = new Size(30, 40);
            shot.SizeMode = PictureBoxSizeMode.StretchImage;
            Controls.Add(shot);
            shooting.Add(shot);
            firing.Play();

        }

I tried using the whole path of the photo instead of its name but it still wouldn't work. The photo is on the program file on the PC


Solution

  • The problem is most likely that your photo is not in the same directory as your executable file. When you use a relative path like "bullet.png", the program will look for the file in the same directory as the executable. If the photo is not there, it will not be found and the program will not be able to display it.

    To fix this, you can either move the photo to the same directory as the executable, or you can use an absolute path to the photo. An absolute path would be something like "C:\Users\YourName\Documents\MyGame\bullet.png". Keep in mind absolute paths are absolutely only for testing purposes as they most likely won't work on other computers

    If moving to the executable file's directory doesn't work try moving it to your solution's directory, sometimes Visual Studio will use that as the active directory, see what works.