Merging .NET application with its configuration

2019-07-24 12:15发布

问题:

I have a .NET executable.

For this executable, I need to merge it together with its configuration to get only one file.

This configuration can be anything, not only app.config file and it is static and will never change after merging. But it will be dynamic before merging. So I can end up with many executables each with different configuration build-in.

The merging process will be run programaticaly, with configuration being parameters and needs to be reasonably fast.

Anyone had similiar problem? I was thinking about merging using ILMerge with resources, but I dont know if it can do it. Or I can build whole exacutable with devenv, this requires VisualStudio to be installed on the PC, that is merging, which will not always be the case. And I don't think it will be fast enough.

Edit: After looking around for a second and trying something, maybe Mono.Cecil can do the work. In my executable, I will create a static Configuration class, which will have properties with my configuration. And using IL rewrite, I will change what those properties return. Any opinions about this?

回答1:

You can change the build property of the file to Embedded Resource and the Copy to Output to false. Then, to get the config info, use code like this:

string ReadEmbeddedResource(string fileName) {
  Assembly app = Assembly.GetExecutingAssembly();

  // This will be the fully-qualified name
  Stream resource = app.GetManifestResourceStream(app.GetName().Name + "." + fileName);

  StreamReader reader = new StreamReader(resource);
  return reader.ReadToEnd();        
}

Now, the app.config file should no longer be copied to your build directory and you can still reference from within your exe.



回答2:

You can use the "Embedded Resource" option included with visual studio. Select the file that you want to merge into the EXE from the Solution Explorer, Right Click, Select Properties. In the properties window set the "Build Action" to "Embedded Resource". Add that file to the project resources as per usual.



回答3:

Because the EXE's format outputted by a managed compiler are still technically in the PE format, I would create a new section at the end of the PE, mark it as 'READ ONLY' and put my data there. But I think that's a bit overboard for what you are looking for



回答4:

Are you looking for something like an embedded database?

Then in your build you can have a DB-prep be a step in the process, copy the right DB to your solution before the project/solution is compiled.

We've done this to modify Assembly version files pre-build, but any automated build tool (MSBuild, NAnt) could do this with some creativity.