简体   繁体   中英

Compile c# code from file on memory

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?

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#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM