Wednesday, December 23, 2009

Generate assembly from C# code file dynamically

Simple code for creating the assemblies dynamically from a C# code file.



public bool CompileSource(string sourceFile, string targetAssembly, string [] references)
        {
            // delete existing assembly first
            if (File.Exists(targetAssembly))
            {
                try
                {
                    // this might fail if assembly is in use
                    File.Delete(targetAssembly);
                }
                catch (Exception ex)
                {
                    this.ErrorMessage = ex.Message;
                    return false;
                }
            }

            // read the C# source file
            StreamReader sr = new StreamReader(sourceFile);
            string fileContent = sr.ReadToEnd();
            sr.Close();

            // set up compiler and add required references
            ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
            CompilerParameters parameter = new CompilerParameters();
            parameter.OutputAssembly = targetAssembly;
            foreach(string reference in references)
            {
        parameter.ReferencedAssemblies.Add(reference);
            }
           
            // Do it: Final compilation to disk
            CompilerResults results = compiler.CompileAssemblyFromFile(parameter, sourceFile);

            if (File.Exists(targetAssembly))
                return true;

            // flatten the compiler error messages into a single string
            foreach (CompilerError err in results.Errors)
            {
                this.ErrorMessage += err.ToString() + "\r\n";
            }

            return false;
        }

1 comment:

  1. hi,

    First of all. Thanks very much for your useful post.

    I just came across your blog and wanted to drop you a note telling you how impressed I

    was with the information you have posted here.

    Please let me introduce you some info related to this post and I hope that it is useful

    for .Net community.

    There is a good C# resource site, Have alook

    http://www.csharptalk.com

    simi

    ReplyDelete