mercredi 3 août 2016

Keeping a console application alive in C#

I just created a basic console application that uses my framework to compile C# code from a text file.

The way you would run this is "SecureCodeBridge.exe File.txt", this text file contains code that creates and shows a windows form which works fine.

The problem is that because my application is a console application, it will exit as soon as the method from the text file is invoked (the Form shows for a second and disappears as the console application exits...)

This is the code of my console application:

static void Main(string[] args)
{
    string entString = args[0];

    if(System.IO.File.Exists(entString))
    {
        string entContents = System.IO.File.ReadAllText(entString);
        SecureCode sC = new SecureCode(entContents);
        CompilerResults cR = sC.Compile();

        if(cR.Errors.Count > 0)
        {
            //Abort!
            foreach(CompilerError cE in cR.Errors)
            {
                Console.WriteLine(cE.ErrorText);
            }
        }
        else
        {
            sC.Run(cR);
        }
    }
}

And this is the code my framework uses to compile and run the code:

public class SecureCode
{
    string code;
    public SecureCode(string source)
    {
        code = source;
    }

    public CompilerResults Compile()
    {
        Dictionary<string, string> providerOptions = new Dictionary<string, string>
        {
            {"CompilerVersion", "v3.5"}
        };
        CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

        CompilerParameters compilerParams = new CompilerParameters
        {
            GenerateInMemory = true,
            GenerateExecutable = false
        };
        compilerParams.ReferencedAssemblies.Add("System.dll");
        compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
        compilerParams.ReferencedAssemblies.Add("System.Drawing.dll");

        CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, code);

        return results;
    }

    public void Run(CompilerResults results)
    {
        object o = results.CompiledAssembly.CreateInstance("Code.Class");
        MethodInfo mi = o.GetType().GetMethod("Main");
        mi.Invoke(o, null);
    }
}

Is there some way to keep the console application alive while the method is being invoked? (For example, a form being shown)





Aucun commentaire:

Enregistrer un commentaire