Load picturebox image in C# from file in relative path

Ivo77 picture Ivo77 · Jul 15, 2014 · Viewed 30.8k times · Source

I have a picturebox image in a Windows Form Solution. After user selects an item from a database, I want to load an image into this picturebox. The filename of the image will come from the database and all images must be stored in a subfolder of the application folder (\Images). I don't want to include all these (2000-3000 images) in my solution, besides, more images will be added by users as the database grows. Also, I don't want to code an absolute path. So this is not what I want:

pictureBox.Image = Image.FromFile(@"C:\Program Files\Application\Images\" + dbase.filename);

I want to code a relative path to the image folder, so regardless of where the application will be installed, the images can be loaded from this particular subfolder. I've tried things like these, using a temporary test-image called "test.jpg":

pictureBox.Image = Image.FromFile(@"Images\test.jpg");
pictureBox.Image = Image.FromFile(@"..\Images\test.jpg");
pictureBox.Image = Image.FromFile(@"|DataDirectory|\Images\test.jpg");

But these don't work. I can only get it to work with an absolute path, like "C:\Images\test.jpg". What should I do?

Answer

Code Maverick picture Code Maverick · Jul 15, 2014

Have you tried the PictureBox.Load Method?

If the url parameter indicates a local file, the recommended format is a local file path. For example, an image file named myPicture.jpglocated atc:\ would be accessed by passing c:\myPicture.jpg for the url parameter. A full path, such as http://www.contoso.com/path/images/image.jpg, or a relative path, such as ./images/image.jpg, can be used. If a relative path is used, it will be considered relative to the working directory. A call to the Load method sets the ImageLocation property to the value of url.