Beispiel #1
0
        /// <summary>
        /// Compile the specified 'code' into an executable assembly. If 'assemblyFileName'
        /// is null then compile to an in-memory assembly.
        /// </summary>
        /// <param name="code">The code to compile.</param>
        /// <param name="referencedAssemblies">Any referenced assemblies.</param>
        /// <param name="sourceName">Path to a file on disk containing the source.</param>
        /// <returns>Any compile errors or null if compile was successful.</returns>
        private Compilation CompileTextToAssembly(string code, IEnumerable <MetadataReference> referencedAssemblies, out string sourceName)
        {
            string assemblyFileNameToCreate = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), tempFileNamePrefix + Guid.NewGuid().ToString()), ".dll");

            bool        VB = code.IndexOf("Imports System") != -1;
            Compilation compilation;

            if (VB)
            {
                sourceName = Path.GetFileNameWithoutExtension(assemblyFileNameToCreate) + ".vb";
                SyntaxTree syntaxTree = VisualBasicSyntaxTree.ParseText(
                    code,
                    new VisualBasicParseOptions(),
                    path: sourceName);

                VisualBasicSyntaxNode syntaxRootNode = syntaxTree.GetRoot() as VisualBasicSyntaxNode;
                var encoded = VisualBasicSyntaxTree.Create(syntaxRootNode, null, sourceName, System.Text.Encoding.UTF8);
                compilation = VisualBasicCompilation.Create(
                    Path.GetFileNameWithoutExtension(assemblyFileNameToCreate),
                    new[] { encoded },
                    referencedAssemblies,
                    new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));;
            }
            else
            {
                sourceName = Path.GetFileNameWithoutExtension(assemblyFileNameToCreate) + ".cs";
                SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(
                    code,
                    new CSharpParseOptions(),
                    path: sourceName);

                CSharpSyntaxNode syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
                var encoded = CSharpSyntaxTree.Create(syntaxRootNode, null, sourceName, System.Text.Encoding.UTF8);
                compilation = CSharpCompilation.Create(
                    Path.GetFileNameWithoutExtension(assemblyFileNameToCreate),
                    new[] { encoded },
                    referencedAssemblies,
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            }
            return(compilation);
        }