Reputation: 31
I am displaying an image on a canvas. When using an absolute path everything works perfectly. However when i try to use a relative path, my code runs but the image is not loaded. I need to use a relative path because we are working on a group project with git. The folder with my images is inside the project folder.
private void ShuffleCardsClick(object sender, RoutedEventArgs e)
{
computerDeck.ShuffleDeck();
playerDeck.ShuffleDeck();
dealButton.IsEnabled = true;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"card_images\cardback.png", UriKind.RelativeOrAbsolute);
bi.UriSource = new Uri(@"C:\Users\Windows\Documents\GitHub\NetEssentials_H1\
Kaartspelen\KoetjeMelken\card_images\cardback.png");
bi.EndInit();
Image card = new Image();
card.Source = bi;
card.Margin = new Thickness(0, 0, 0, 0);
card.Width = computerDeckCanvas.Width;
card.Height = computerDeckCanvas.Height;
computerDeckCanvas.Children.Add(card);
}
Upvotes: 0
Views: 857
Reputation: 27
If you are working with an MVC project then you can use Server.MapPath("your/path")
which will create a relative path for you.
More info: MSDN
Also for class libraries i have used the following before which worked a treat:
var appDomain = System.AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
var path = Path.Combine(basePath, "EmailTemplates");
Upvotes: 0
Reputation: 5771
A relative path in a .NET client application is always relative to your working directory. By default, if you run your application from within Visual Studio, the working directory is bin\Debug (or bin\Release, if you run in Release mode).
Therefore, the quickest fix would be to specify that Visual Studio should copy your files to the target folder. However, that does not solve your problem in case the user wants to execute your program with a different working directory. If you want to avoid a crash in that scenario, you have to compute the absolute path of the image files, for example taking the absolute path of the executing assembly as a basis.
Otherwise, you can also include your images as resources.
Upvotes: 2