Accessing Resources in a C# WPF Application (Same Assembly)
c#, visual-studio-2012, wpf, xaml
Solution
Try adding the component-part to your Pack URI like this
pack://application:,,,/AssemblyName;component/ResourceName
where AssemblyName is the name of your assembly. So for your case, the following statement should work:
bar.Source = new Uri("pack://application:,,,/AssemblyName;component/foofiles/page1.foo");
More practically, try the relative pack uri notation:
bar.Source = new Uri("AssemblyName;component/foofiles/page1.foo", UriKind.Relative));
For stream reading resources use
var streamResourceInfo = Application.GetResourceStream(uri);
using (var stream = streamResourceInfo.Stream)
{
// do fancy stuff with stream
}
Problem
(Before I jump into the nitty-gritty, I want to set the context: I'm trying to load a WPF frame with the contents of an .html file that I'm including in my project as a resource.) I create a new WPF Application; I add a new folder called 'foofiles' to the project, and I add a couple of files (page1.foo and page2.foo) to that folder. For each newly added .foo file, I right-click on it, go to "Properties," and set the Build Action to 'Resource,' and the Copy To Output Directory to "Copy always." I want to be able to access those files both in XAML: ``` <Frame x:Name="bar" Source="/foofiles/page1.foo"/> ``` And in procedural code: ``` private void someFunc() { bar.Source = new Uri("/foofiles/page1.foo"); } ``` But I just can't figure out why this doesn't work -- I get a "Format of the URI could not be determined." In the code-behind, I tried doing this: ``` private void someFunc() { bar.Source = new Uri("pack://application:,,,/foofiles/page1.foo"); } ``` which didn't 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 should be able to use that file per my examples above. Also, I would like to use that file like this: ``` 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!