emansour619
emansour619

Reputation: 25

Refrain from using local path for image in C#

I am loading an image in my program with this code:

Image img = new Bitmap(@"C:\Users\******\Desktop\*****\bin\Debug\image.png");

I would like to keep the location static so I don't have to manually edit the path when I run the program on a different PC.

I am experimenting with the apps.config file as I have heard this is where my solution will lie.

Any help with this would be appreciated!

Upvotes: 0

Views: 74

Answers (3)

PMF
PMF

Reputation: 17185

The static property

AppDomain.CurrentDomain.BaseDirectory

points to the path from where the application was started, even if the current directory points somewhere else. You can use this to locate files that are in the same directory as the executable. However, for small images (i.e. GUI components), embedding them as resources is the way to go.

Upvotes: 0

Robert Altman
Robert Altman

Reputation: 181

Why not use Environment.SpecialFolder? This isn't static, obviously, but you wouldn't have to edit anything. You would really only have to create the folders on the desktop if they don't already exist.

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Or use System.Environment.CurrentDirectory since it looks like that's where you're putting it anyway...

Image img = new Bitmap(Environment.CurrentDirectory + @"\image.png");

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190907

A better solution would be to embed it in a resx file as part of your assembly. That way you wouldn't have to worry about the file being located any differently.

Upvotes: 2

Related Questions