I am trying to produce generic .NET executables that can be customized by changing the embedded resources. Ideally, I would like to be able to do this with a compiled executable, but it would also be acceptable to use some sort of intermediate representation. The key is that I need to be able to do this with a program, not manually.
Consider a C# program that looks something like this:
namespace MyProgram {
public class Program {
public static void Main(string[] args)
{
using(var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProgram.Resources.foo"))
{
// ignore stream == null
DoStuff(stream);
}
}
}
}
This will work as expected when some resource is embedded and named "foo". However, what I am trying to accomplish is building the program without the resource embedded, and then 'post-processing' the program to embed the resource. In fact, it would be even better if it's possible to both embed a new resource with an arbitrary name and add it to the resource manifest, so that at runtime the program can read the embedded resources and act on them.
Is there a way to programmatically embed new resources into a compiled .NET executable?
Say you have a project called Resources.csproj
.
You could copy resources into a specific directory (e.g. Content).
Project directory structure
----------------------------
Properties
AssemblyInfo.cs
Content
Item1.png
Item2.png
You could then dynamically update your csproj file using XDocument
or similar to include your content as embedded resources.
<Project>
<ItemGroup>
<EmbeddedResource Include="Content\Item1.png" />
<EmbeddedResource Include="Content\Item2.png" />
</ItemGroup>
</Project>
You could then compile the project however you like.
msbuild Resources.sln
Your resources should then be available in the output assembly. The advantage is that this approach avoids the overhead of dealing with CodeDom
.