Steve Steve - 1 year ago 127
C# Question

Uri throws invalid port for WPF style uri

I am trying to initialize a BitmapImage instance in code with wpf style uri.

BitmapImage icon = new BitmapImage(new Uri("pack://application:,,,/MyAssembly;component/Icons/someIcon.ico", UriKind.Absolute));

But the problem is
new Uri

Invalid URI: Invalid port specified.

what have I done wrong?

Answer Source

The issue here is that you're attempting to create the Uri in an application that isn't a normal WPF application. Uri has a number of built in 'schemes' that are registered with the UriParser.

The UriParser class enables you to create parsers for new URI schemes. You can write these parsers in their entirety, or the parsers can be derived from well-known schemes (HTTP, FTP, and other schemes based on network protocols).

WPF adds a parser for the 'pack' scheme when a System.Windows.Application is created, which is the normal entry point for a WPF application. In your case you can just add a call to this in your composition root:

new System.Windows.Application();