I have an embedded HTML resource (helloworld.htm) inside my Visual Studio project. (Ie, I\'ve added an HTML file to the project and set its properties to \"Embedded Resource
This is the little helper class and how to call it:
How to call:
StreamResourceInfo info =
ResourceHelper.GetResourceStreamInfo(@"Resources/GraphicUserGuide.html");
if (info != null)
{
WebBrowser.NavigateToStream(info.Stream);
}
Helper class:
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
namespace HQ.Wpf.Util
{
public class ResourceHelper
{
// ******************************************************************
///
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
///
/// Path without starting slash
/// Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly
///
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
return new BitmapImage(ResourceHelper.GetLocationUri(pathInApplication, assembly));
}
// ******************************************************************
///
/// The resource should be defined as 'Resource' not as 'Embedded resource'.
///
/// The path start with folder name (if any) then '/', then ...
/// If null, then use calling assembly to find the resource
///
public static Uri GetLocationUri(string pathWithoutLeadingSlash, Assembly assembly = null)
{
if (pathWithoutLeadingSlash[0] == '/')
{
pathWithoutLeadingSlash = pathWithoutLeadingSlash.Substring(1);
}
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
return new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathWithoutLeadingSlash, UriKind.Absolute);
}
// ******************************************************************
///
/// The resource should be defined as 'Resource' not as 'Embedded resource'.
/// Example:
/// StreamResourceInfo info = ResourceHelper.GetResourceStreamInfo(@"Resources/GraphicUserGuide.html");
/// if (info != null)
/// {
/// WebBrowser.NavigateToStream(info.Stream);
/// }
///
/// The path start with folder name (if any) then '/', then ...
/// If null, then use calling assembly to find the resource
///
public static StreamResourceInfo GetResourceStreamInfo(string path, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
return Application.GetResourceStream(ResourceHelper.GetLocationUri(path, assembly));
}
// ******************************************************************
}
}