Dim
Dim

Reputation: 4837

WPF load image from folder

I have images that is not located in resources but on the disk. The folder is relative to application. I used:

Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../MyImages /myim.jpg", Directory.GetCurrentDirectory())));
Overview_Picture.Source = new BitmapImage(uriSource);

But those type of code created many problems and messed up GetCurrentDirectory returns that sometime ok and some times not.

So, MyImages folder is located next to Debug folder, how can I use them images there and not as I done, In some other more right way?

Upvotes: 1

Views: 9012

Answers (2)

Clemens
Clemens

Reputation: 128136

An alternative to constructing an absolute Uri from a relative file path would be to just open a FileStream from the relative path, and assign that to the BitmapImage's StreamSource property. Note however that you also have to set BitmapCacheOption.OnLoad when you want to close the stream right after initializing the BitmapImage.

var bitmap = new BitmapImage();

using (var stream = new FileStream("../MyImages/myim.jpg", FileMode.Open))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
    bitmap.Freeze(); // optional
}

Overview_Picture.Source = bitmap;

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

As mentioned oftentimes here on SO, the GetCurrentDirectory method does by definition not always return the directory your assembly resides in, but the current working directory. There is a big difference between the two.

What you need is the current assembly folder (and the parent of that). Also, I'm not sure whether it is wanted that the pictures are one folder above the installation folder (which is basically what you're saying when you say they are one level above the Debug folder - in real life that would be one folder above the folder the application is installed to).

Use the following:

string currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string currentAssemblyParentPath = Path.GetDirectoryName(currentAssemblyPath);

Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/MyImages/myim.jpg", currentAssemblyParentPath)));

Also, there's a stray space after MyImages, which I removed.

Upvotes: 2

Related Questions