1

I want to compile my codes from a file straight into memory (Runtime-Compilation or RunPE method).

This is the code i use:

var param = new CompilerParameters
        {
            GenerateExecutable = false,
            IncludeDebugInformation = false,
            GenerateInMemory = true
        };
        param.ReferencedAssemblies.Add("System.dll");
        param.ReferencedAssemblies.Add("System.Xml.dll");
        param.ReferencedAssemblies.Add("System.Data.dll");
        param.ReferencedAssemblies.Add("System.Core.dll");
        param.ReferencedAssemblies.Add("System.Xml.Linq.dll");

        var codeProvider = new CSharpCodeProvider();
        // The file contaning the codes is here
        var results = codeProvider
            .CompileAssemblyFromFile(param, @"C:\Users\xxx\Desktop\code.txt");

        if (results.Errors.HasErrors)
        {
            foreach (var error in results.Errors)
            {
                Console.WriteLine(error);
            }
        }
        else
        {
            results.CompiledAssembly.CreateInstance("Program");
        }

This will give me no errors in debugg but Not working too. Just in debugging output im seeing this:

Loaded '3kp0asrw'. Module was built without symbols.

Other things looks fine.

And this is the code in code.txt file that suppose to simply write 3 lines of text and show a message in console:

internal class Program
{
    private static void Main(string[] args)
    {
        string[] lines = { "First line", "Second line", "Third line" };
        System.IO.File.WriteAllLines(@"C:\Users\xxx\Desktop\writeHere.txt", lines);
        Console.WriteLine("Some Random Text!");
    }
}

Question: What i am missing here? Do You know any other way to run code from file or source straight in memory (AKA RunPE methods)? Can you show me a simple example?

Note: I want to do it for much bigger code and Automate it for later uses, like what .net crypters do in stub files, no need for specifying class name and ... every time. Is it possible?

2
  • My guess is that compiling and running are two separate things here. I'm not familiar with the API, but I would check for a complete example that both compiles and runs the code. Commented Jan 8, 2018 at 11:02
  • try reading headsigned.com/article/… Commented Jan 8, 2018 at 11:04

1 Answer 1

3

I recently did the same ,You can update the following according to your requirement ,

string[] code = {
                                "using System; using System.Data"+
                                "namespace CodeFromFile"+
                                "{"+
                                "   public class CodeFromFile"+
                                "   {"+
                                "       static public int Add(int a ,int b)"+
                                "       {"+
                                "           return a+b;
                                "       }"+
                                "   }"+
                                "}"
                                    };

And pass this code to

static int CompileAndRun(string[] code)
    {

        CompilerParameters CompilerParams = new CompilerParameters();
        string outputDirectory = Directory.GetCurrentDirectory();

        CompilerParams.GenerateInMemory = true;
        CompilerParams.TreatWarningsAsErrors = false;
        CompilerParams.GenerateExecutable = false;
        CompilerParams.CompilerOptions = "/optimize";

        string[] references = { "System.dll", "System.Data.dll" };
        CompilerParams.ReferencedAssemblies.AddRange(references);

        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code);

        if (compile.Errors.HasErrors)
        {
            string text = "Compile error: ";
            foreach (CompilerError ce in compile.Errors)
            {
                text += "rn" + ce.ToString();
            }
            throw new Exception(text);
        }

        Module module = compile.CompiledAssembly.GetModules()[0];
        Type mt = null;
        MethodInfo methInfo = null;

        if (module != null)
        {
            mt = module.GetType("CodeFromFile.CodeFromFile");
        }

        if (mt != null)
        {
            methInfo = mt.GetMethod("Add");
        }

        if (methInfo != null)
        {                
            return (int)methInfo.Invoke(null, new object[] { 5,10});
        }

        return null;
    }

Source : Compiling and Running code at runtime and Dynamically Compiling C#

Sign up to request clarification or add additional context in comments.

10 Comments

Tried this and worked with your Example but this doesn't work with bigger codes. Does it ? I stored my code from file to a string[] but does not work with, think it needs a lot of tweaks.
is it throwing some exception ?
place a break point at if (compile.Errors.HasErrors) { string text = "Compile error: "; foreach (CompilerError ce in compile.Errors) { text += "rn" + ce.ToString(); } throw new Exception(text); } this will confirms either code written in file is compiling successfully or not.
No error or exception, can you do it for files ? im changing CompileAssemblyFromSource to CompileAssemblyFromFile and further changes but again no errors and nothing will happen.
I think problem is with code you are reading from file. If you can try with executing the working example from file ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.