سؤال

Possible Duplicate:
How to programatically build and compile another c# project from the current project

Lets say we have an application named Program1.exe so when i click that exe that program has to create another exe lets say Program2.exe which write "hello world" on screen. So I think its possible using command line tool of visual studio using csc command in code, anyway if its possible can that Program2.exe replace Program1.exe? I mean that Program1.exe can re-compile in runtime?

هل كانت مفيدة؟

المحلول

sure you can do this, have a look at the class: Microsoft.CSharp.CSharpCodeProvider

and at this article: Compiling and Executing Code at Runtime

P.S. you are not really calling the csc command from code, but something way lower, in my understanding... which is good anyway as you use managed classes and not an external tool.

نصائح أخرى

While Program1.exe is running, Windows should deny write access to the file... If I understood correctly your question, I'd say that definitely it's not the way to go. To change itself during runtime, a program should use some form of Reflection.

If you want to do efficiently, look at Emit, that gives you full bytecode access power (and related danger). Some years ago I used a project from CodeProject, that helped me to work out the details. I was working on .NET 2.0, now surely there is something more recent (like this).

Or you could use CSharpCodeProvider, and build assemblies to be loaded (either compile from source or from a tree representation).

You could as well use csc to compile an assembly, and load that in your running program. If you go this way, you'll need some attention in Assembly loading. This link could be useful.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top