3

I'm trying to get an image from a certain path, but the path must only be referenced from the application's current folder and not from the Local C: drive.

My reason for this is because the application is going to get published soon and I can't reference the image to the same local location on my current PC, because the application is going to be used on a lot of other PC's and the path would not work on other someone else's computer.

This is the current path that works:

SetDefaultImage(new Binary(File.ReadAllBytes("C:\\Users\\mclaasse\\Desktop\\Haze Update\\Haze\\Haze\\Icons\\user6.jpg")));

And this is how I need it to be:

SetDefaultImage(new Binary(File.ReadAllBytes("Haze\\Icons\\user6.jpg")));

But i'm getting the error:

Could not find a part of the path 'C:\Haze\Icons\user6.jpg'.

Is there a simple work around for getting my path to work?

CareTaker22
  • 1,260
  • 3
  • 18
  • 36
  • Your answer probaby lies here : http://stackoverflow.com/a/17405207/2245256 – Irwene Feb 26 '16 at 10:41
  • 2
    Why not load the image from an assembly resource? – Clemens Feb 26 '16 at 10:41
  • Possible duplicate of [How to read existing text files without defining path](http://stackoverflow.com/questions/17405180/how-to-read-existing-text-files-without-defining-path) – Irwene Feb 26 '16 at 10:43
  • @Clemens Thanks for the comment man! How would I load it from a assembly resource? – CareTaker22 Feb 26 '16 at 10:44
  • @CareTaker22 From MSDN :) https://msdn.microsoft.com/en-us/library/yf17tthe(v=vs.90).aspx. There are other solutions however if you want to load it directly from the markup in which case, you should read : http://stackoverflow.com/questions/9419611/how-to-refer-to-embedded-resources-from-xaml – Irwene Feb 26 '16 at 10:46

2 Answers2

2

Not sure if this is exactly what you need, but provided that you have an image file user6.jpg in your Visual Studio project in a project folder named Images, and the Build Action of the image file is set to Resource, you could simply load it from a Resource File Pack URI:

var image = new BitmapImage(new Uri("pack://application:,,,/Images/user6.jpg"));
Clemens
  • 123,504
  • 12
  • 155
  • 268
1

None of the references worked for me(I don't know why), but this worked:

string directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string filePath = Path.Combine(directory, "Icons\\user6.jpg");

Then check if the file that you are looking for exists:

if (!File.Exists(filePath))
{
    MessageBox.Show("The default image does not exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
    ...
}
CareTaker22
  • 1,260
  • 3
  • 18
  • 36