Question

I have a console app that should, when given a particular command-line argument, write a skeleton configuration file for my app to a specified directory. Currently, that skeleton config file now lives in my assembly (under a t4 template that I use to generate it at compile time).

When my app is run with the relevant argument, I want to be able to load the results of my t4-processed config file into memory at run time and then write it to an arbitrary location on disk.

I can't figure out how to reference and load the file in my solution in my C# code. Is it even possible to embed a file resource like this into an assembly and reference it from code? Or do I need to put the file on the filesystem as part of an install process? I'd rather not have to do the latter if possible.

Any help or advice would be most appreciated. :)

Was it helpful?

Solution

Oops. Figured it out, after making some inferences based on this stackoverflow question: "How to embed a text file in a .NET assembly?"

The trick is to set the file's Build Action property to "Embedded resource." (Note that you're setting this for the result of the t4 template generation, not the the template itself.)

enter image description here

Then it will be embedded in your assembly and you can reference it in code.

var assembly = Assembly.GetExecutingAssembly();
string configFileContents;
using(StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("MySolutionNamespace.ContainingFolder.SiteConfiguration.json"), Encoding.Unicode))
{
    configFileContents = reader.ReadToEnd();
}

Console.WriteLine(configFileContents);
Console.ReadKey();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top