Search code examples
c#compiler-constructionresourcesembedded-resource

How can I embed a string resource and retrieve it after compiling with CodeDom?


I feel like this question might have been answered already but I cannot find an answer that I understand and that is specific to my example, so I'll ask.

I have a C# application that compiles some code and I want to be able to embed a String resource (called someString) that I have inside of my Resources.resx file. Then I want to be able to access that embedded resource in the compiled program. However, I am struggling to access the resource file as when I run the compiled program it says that the Stream cannot be null.

Here is my example code:

string codeString =
        @"using System;
        using System.IO;
        using System.Reflection;

        namespace SomeProgram
        {
            class MyClass
            {
                static void Main(string[] args)
                {
                    Assembly resourceAssembly = Assembly.GetExecutingAssembly();
                    StreamReader stream = new StreamReader(resourceAssembly.GetManifestResourceStream(""Resources.someString""));
                    string someStringValue = stream.ReadToEnd();

                    Console.WriteLine(someStringValue);
                    Console.ReadLine();
                }
            }
        }";


// Compiler Code
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string outFile = "output.exe";

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = outFile;
parameters.EmbeddedResources.Add("..\\..\\Properties\\Resources.resx");
parameters.EmbeddedResources.Add("..\\..\\Properties\\Resources.Designer.cs");

CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, codeString);

Am I accessing the embedded resource in the wrong way in the compiled code?


Solution

  • Answer to my own question: Found a way (that probably isn't the best way to do it) but it involves reading the stream from the embedded resource file and then later parsing it for the required string value.

    StreamReader stream = new StreamReader(resourceAssembly.GetManifestResourceStream(""Resources.resx""))