Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

wpf - Xaml - Bitmap UriSource - absolute path works, relative path does not, why?

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:LongPathSolutionFolderProjectFolderinDebugpath4.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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...