0

I have searched for an answer to my problem and tried many solutions but cant solve it

I have a windows form application and I have to set the image in a picture box dynamically and I have succeeded doing this with the following code

    pictureBox2.Image = Image.FromFile("C:/Users/user/Documents/College Work/4th Year/Advanced Net/Projects/Game/Resources/" + Quiz1FromFile.Q1Ans + ".jpg"););

How do I modify the above path so that it will work if i move the location of the project. "Game" is the name of the windows form project

  • 1
    Look at two answers below. Both are valid. But it is depends, what you want to do. Do you want your application always look into specific relative path or you want to have arbitrary path? If the arbitrary path, add `app.config` file and use settings. If you want static relative path, use `Environment.CurrentDirectory` and go from there. so if your images always in your bin\images you will need to write `Image.FromFile(Path.combine(Environment.CurrentDirectory, "images", "image1.jpeg"))` – T.S. Oct 25 '13 at 21:55
  • I agree with @T.S. because for desktop apps, you cannot control how it is launched (working directory), then it is unsafe to use relative paths (which will break if working directory is not what you expected). Using absolute paths is safer. – Lex Li Oct 26 '13 at 02:03

2 Answers2

1

The best approach is to add an ApplicationSettings in the settings tab of your project property.
Call this property, for example, "ImagePath" and set this property to your default development path.

After doing that, you will have an entry in your app.config file (that becomes, when compiled YourApplicationName.exe.Config) with the value of your default path.

<applicationSettings>
    <YourAppNamespace.Properties.Settings>
        <setting name="ImagePath" serializeAs="String">
            <value>C:/Users/user/Documents/College Work/4th ......</value>
        </setting>
    <(YourAppNamespace.Properties.Settings>
</applicationSettings>

This file will be distributed with your application and you could change that path using your deployment procedure.

In code you could refer to the path stored in the config file using

string imagePath = Properties.Settings.Default.ImagePath;
pictureBox2.Image = Image.FromFile(Path.Combine(imagePath, Quiz1FromFile.Q1Ans,  ".jpg"));

In this way you don't hard code the path to your image folder inside the application and you don't need to handle relative paths. You have only to set this value on the target machine to the storage of your image files.

Steve
  • 213,761
  • 22
  • 232
  • 286
0

You need to two things. First, the file name should be the relative path related to where you executable will be. The second thing is that you'll need to make sure the images are actually there. You can use the post build event to copy the images to the DestinationFolder path.

Take a look here.

Community
  • 1
  • 1
Lior Ohana
  • 3,467
  • 4
  • 34
  • 49