Search code examples
c#variablescsharpcodeprovider

How to pass a variable with CSharpCodeProvider?


I need to create an EXE file with my application, I can pass strings with manipulating the string format but I cannot pass the other variables that I need to ex:byte array, here is my code if this helps:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Windows;

namespace ACompiler.CompWorker
{
    class CompilerWorker
    {
        public static byte[] testarray = SomeClass.SomeArray;
        public static string Key = "Testkey12";
        public static void Compile()
        {
            CSharpCodeProvider CompileProvider = new CSharpCodeProvider();

            CompilerParameters CompileProviderParameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, AppDomain.CurrentDomain.BaseDirectory + "Compiled.exe", true);
            CompileProviderParameters.GenerateExecutable = true;


            string test= @"using System;

namespace Tests
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte[] Content = " + testarray + @";
                string Key = """ + Key + @""";
                Console.WriteLine(""Key: "" + EKey);
                Console.WriteLine(Content);
                Console.ReadLine();
            }
        }
    }
";

            var Result = CompileProvider.CompileAssemblyFromSource(CompileProviderParameters, test);
        }
    }
}

Basically I want to move the "testarray" into the compiled app, I hope someone can point me to the right direction!


Solution

  • The trick is to "serialize" the data back in to code the compiler can compile. Try this:

    var arrayCode = "new byte[] { " + string.Join(", ", testarray) + " }";
    
    string test = @"using System;
    namespace Tests
        {
            class Program
            {
                static void Main(string[] args)
                {
                    byte[] Content = " + arrayCode + @";
                    string Key = """ + Key + @""";
                    Console.WriteLine(""Key: "" + EKey);
                    foreach(byte b in Content)
                    {
                        Console.WriteLine(b.ToString());
                    }
                    Console.ReadLine();
                }
            }
        }
    ";
    

    Keep in mind, you can't do Console.WriteLine on a byte array object and have it spit out each item. You will have to iterate over the items to print them out. I updated your code to do it the proper way.