Accessing resources in a WPF C # application (same assembly)

(Before I switch to nitty-gritty, I want to establish the context: I am trying to load a WPF frame with the contents of a .html file, which I include in my project as a resource.)

I am creating a new WPF application; I add a new folder to the project called "foofiles", and I add a couple of files (page1.foo and page2.foo) to this folder.

For each newly added .foo file, I right-click on it, go to "Properties" and set the "Create" action to "Resource" and "Copy to output directory" "Always copy."

I want to have access to these files as in XAML:

<Frame x:Name="bar" Source="/foofiles/page1.foo"/> 

And in the procedural code:

 private void someFunc() { bar.Source = new Uri("/foofiles/page1.foo"); } 

But I just can’t understand why this does not work - I get "URI format cannot be defined".

In code, I tried to do this:

 private void someFunc() { bar.Source = new Uri("pack://application:,,,/foofiles/page1.foo"); } 

which did not throw an exception, but my main window crashed.

In my thinking, if I add a file of any type to my project, and if I mark it as "Resource" in "Build Action", I will have to use this file for my examples above. In addition, I would like to use this file as follows:

 private void someOtherFunc() { System.IO.StreamReader reader = new System.IO.StreamReader("/foofiles/page1.foo"); string bar = reader.ReadToEnd(); } 

Any help would be appreciated ... thanks in advance!

+4
source share
1 answer

Try adding the component part to your package URI, for example

 pack://application:,,,/AssemblyName;component/ResourceName 

where AssemblyName is the name of your assembly. Therefore, for your case, the following expression should work:

 bar.Source = new Uri("pack://application:,,,/AssemblyName;component/foofiles/page1.foo"); 

More practical, try the package uri convention:

 bar.Source = new Uri("AssemblyName;component/foofiles/page1.foo", UriKind.Relative)); 

For stream read resources, use

 var streamResourceInfo = Application.GetResourceStream(uri); using (var stream = streamResourceInfo.Stream) { // do fancy stuff with stream } 
+7
source

Source: https://habr.com/ru/post/1497277/


All Articles