Create classes and compile it from c#

Go To StackoverFlow.com

1

I am creating a custom code generator using c#... this generator now only creates the bussiness entity from tables of a database. But Now what I want is to create a project that contains this classes and after its creation.... Generate the dll from the project.

Is there a way to do this job?

2012-04-03 22:28
by jcvegan
If you need to create a Visual Studio project, you can reverse engineer the project file fairly easily. If not, just call csc.exe with a command line specifying the files you've generated. It seems fairly simple so I don't understand what you're stuck on, if you are advanced enough to write a program that generates C# code from a database schema - phoog 2012-04-03 22:33
Do you mean you have C# methods and you want to create a *.dll file that somebody can else can add to a project and call these methods - JMK 2012-04-03 22:34
@JMK I have a method that generate a *.cs file. Now I want to group some of this files on a C# project And from that project create a *.dl - jcvegan 2012-04-03 22:55


2

You could use CSharpCodeProvider to compile code to a DLL, like this (found on the internet somewhere):

public static bool CompileCSharpCode(String sourceFile, String outFile)
        { 
            // Obtain an ICodeCompiler from a CodeDomProvider class.
            CSharpCodeProvider provider = new CSharpCodeProvider(); 
            ICodeCompiler compiler = provider.CreateCompiler(); // Build the parameters for source compilation. 
            CompilerParameters cp = new CompilerParameters(); // Add an assembly reference. 
            cp.ReferencedAssemblies.Add("System.dll"); // Generate an class library instead of // a executable. 
            cp.GenerateExecutable = false; // Set the assembly file name to generate. 
            cp.OutputAssembly = outFile; // Save the assembly as a physical file. 
            cp.GenerateInMemory = false; // Invoke compilation. 
            CompilerResults cr = compiler.CompileAssemblyFromFile(cp, sourceFile);
            if (cr.Errors.Count > 0)
            { // Display compilation errors. 
                Console.WriteLine("Errors building {0} into {1}", sourceFile, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    Console.WriteLine(" {0}", ce.ToString());
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Source {0} built into {1} successfully.", sourceFile, cr.PathToAssembly);
            } // Return the results of compilation. 
            if (cr.Errors.Count > 0) { return false; } else { return true; }
        }
2012-04-03 22:41
by Aerik


1

You can either use reflection and use emit or use the Process class to call the c# compiler once you have everything generated.

2012-04-03 22:35
by Micah Armantrout
Ads