views:

285

answers:

2

I would like to take a file that is an IL file, and at run time compile it back to an exe.

Right now I can use process.start to fire off the command line with parameters (ilasm.exe) but I would like to automate this process from a C# service I will create.

Is there a way to do this with reflection and reflection.emit?

While this works:

string rawText = File.ReadAllText(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")), Encoding.ASCII);

rawText = rawText.Replace("[--STRIP--]", guid);

File.Delete(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")));

File.WriteAllText(string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName")),rawText, Encoding.ASCII);

pi = new ProcessStartInfo();
pi.WindowStyle = ProcessWindowStyle.Hidden;
pi.FileName = "\"" + ilasm + "\"";
pi.Arguments = string.Format("c:\\temp\\{0}.il", Utility.GetAppSetting("baseName"));

using(Process p = Process.Start(pi))
{
    p.WaitForExit();
}

It is not ideal as I really would like this to be a streamlined process.

I have seen examples of creating the IL at runtime, then saving, but I need to use the IL I already have in file form and compile it back to an exe.

Thanks.

+4  A: 

What do you mean by a "streamlined process"? Is it not performing well enough for you? I know it feels slightly dirty to spawn a separate process, but it's the simplest way I can think of. With the appropriate permissions you should still be able to do this from a service.

You want something like CSharpCodeProvider but for IL; I don't know of any such class, I'm afraid.

Jon Skeet
Hello Jon,Thanks for the reply. It just feels like you say "clunky". But if this is the only way to do it, then I guess I am stuck calling the command line. Another issue is that this is going to be a service, and might get a little heavy with usage at times. I am not sure how calling a command line util will preform.I just like having a more polished app. Thanks.
nitefrog
@nitefrog: I understand the preference for a library over spawning a process - but if it works, I'd stick with that at the moment. You should probably work out your load and do a load test early on to see whether you'll be able to handle it.
Jon Skeet
Cecil is an assembly manipulation library. It reads and writes assemblies, not IL files.
Jb Evain
@Jb Evain: That's what I suspected. I thought it was worth mentioning as a possible line of enquiry. Will edit.
Jon Skeet
+1  A: 

Actually, many obfuscators, like preemtive and BitHelmet uses ilasm.exe and Process. I think it is the best strategy.

Daniel Dolz