Search code examples
c#.netcsharpcodeprovider

Compiling with a resource file using CSharpCodeDomProvider


I am trying to build a program which will compile one .cs with an xml file as a resource. I have the following code for compiling:

private void Builder(bool run)
{
    CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
    string output = "Output.exe";
    string inputXml = "Input.xml";
    string xml = File.ReadAllText(inputXml);
    string inputCS = Properties.Resources.Program;
    IResourceWriter writer = new ResourceWriter("temp.resources");
    writer.AddResource("Story", xml);
    writer.Close();
    CompilerParameters parameters = new CompilerParameters();
    //Make sure we generate an EXE, not a DLL
    parameters.GenerateExecutable = true;
    parameters.OutputAssembly = output;
    parameters.GenerateInMemory = false;
    parameters.ReferencedAssemblies.Add("System.dll");
    parameters.ReferencedAssemblies.Add("mscorlib.dll");
    parameters.ReferencedAssemblies.Add("System.Xml.dll");
    parameters.EmbeddedResources.Add("temp.resources");
    CompilerResults results = compiler.CompileAssemblyFromSource(parameters, inputCS);
    if (run)
    {
        Process.Start(output);
    }
}

But it has compilation errors and says Properties is not a valid reference from Properties.Resources.Story:

Code from cs file to be compiled

static bool LoadData()
{
    bool result = true;
    Program.doc = new XmlDocument();
    doc.LoadXml(Properties.Resources.Story);
    return result;
}

Update: This is the specific error:

c:\Users\Nick\AppData\Local\Temp\zk14fqrm.0.cs(38,25) : Error CS0103: The name 'Properties' does not exist in the current context

So what about this needs to change to fix this?


Solution

  • Yes, that's to be expected. The Properties.Resources class is automatically generated by a visual studio code generator. It's not a feature of the C# compiler.

    So you still need to add the respective Resources.Designer.cs file, or you need to invoke the code generator as part of your building process and add the autogenerated file to the list of cs files to compile.