How do you read a resource that has build action Resource instead of build-action Embedded Resource. The layout of Resource is waay better, but I want to know how to do it without using the Application (WPF) object.
1 Answer
I have done this for gathering images from the resources where the build action is Resource from an external application. However we have to have a reference to System.Windows.Resources and use the Application.GetResourceStream()
Basically we use the following method.
private static Stream GetResourceStream(string resourcePath)
{
try
{
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
var uri = new Uri(resourcePath);
StreamResourceInfo sri = System.Windows.Application.GetResourceStream(uri);
return sri.Stream;
}
catch (Exception e)
{
return null;
}
}
Now this returns a stream which can then by converted to a byte[] array or used to build other object types.
This could be called like.
//set variables
string myAssembly = "Test.Assembly";
string resourceItem = "resources/myimage.png";
//get the stream
using (var bSteam = GetResourceStream(string.Format("pack://application:,,,/{0};component//{1}", myAssembly, resourceItem)))
{
//covert the stream to a memory stream and return the byte array
using (var ms = new MemoryStream())
{
bSteam.CopyTo(ms);
return ms.ToArray();
}
}
Like I said it does use the Application.GetResourceStream(). If you want to avoid using this method this answer may not be suitable.
Cheers,
1 Comment
sircodesalot
Yeah. I mean I know how to read resources from an assembly, but WPF seems to do a good job at structuring the names (better than an embedded resource). I would like to do this, but in a non WPF application - so I can't really use an
Application object.
ResourceManager?