7

I'm, a WPF & Xaml-noob, for console applications it has worked for me to simply give the relative path to the executable to access a file. It doesn't seem to work in xaml for me. (code at the bottom)
Absolute path works perfectly.

Is it possible in XAML in a WPF-application to access a file by simply using a relative path to the directory of your executable as a valid UriSource? If yes how and if not why not?

I found the following question, where they were talking about adding the file via Visual Studio's "Add existing item", so it seems like a different issue.

How can I set the WPF BitmapImage UriSource property to a relative path?

<Window.Icon>
  <!--absolute path works:-->
  <BitmapImage UriSource="C:\LongPath\SolutionFolder\ProjectFolder\bin\Debug\path4.ico" />

  <!--none of the following relative paths worked:-->
  <!--AppDomain.CurrentDomain.BaseDirectory returns the Debug-folder-->
  <!--<BitmapImage UriSource="path4.ico" />-->
  <!--<BitmapImage UriSource="../path4.ico" />-->
  <!--<BitmapImage UriSource="Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../Debug/path4.ico" />-->
</Window.Icon>
Community
  • 1
  • 1
Jennifer Owens
  • 4,044
  • 5
  • 19
  • 22

2 Answers2

11

URIs can be confusing, as they can refer to both files on disk and resources in the application. So a relative path could be to a resource in the app, when you intend it to be on disk.

You can use the siteoforigin authority to force relative file URIs. This blog explains this more, but here an example:

pack://siteoforigin:,,,/path4.ico
CodeNaked
  • 40,753
  • 6
  • 122
  • 148
  • Is the pack:// URI scheme relevant outside of a Metro execution context? Would that scheme be relevant to a WPF app running under Windows 7? All of these documentation links suggest that the scheme is only relevant to Metro, but we're struggling with this problem under Windows 7. –  Oct 17 '13 at 18:25
  • @ardave - This answer was specific to WPF and posted well before Metro or WinRT was a thing. – CodeNaked Oct 17 '13 at 18:51
4

Relative paths without qualifications look up the referenced file in the application resources, if a path should be relative to the executable you can use pack://siteoforigin:,,,/path4.ico, see Pack URIs on MSDN.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • How does this work for relative paths "Above" the calling file? For example if there are 2 files with the name path4.ico. Is there a hierarchical search that will return the closest file in sense of "depth distance"? – Mechandrius Oct 21 '20 at 12:09
  • @Mechandrius I am pretty sure you have to point directly to the file, so if you want to go up one level the path ends with `../path4.ico` and for up two levels you get `../../path4.ico`. Have never tried that though. – H.B. Oct 21 '20 at 13:01