CodeDOM.cs

Anonymous C# 2/19/2017 1:53:07 PM +00:00

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;
using Microsoft.VisualBasic;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            CodeCompileUnit lUnit = new CodeCompileUnit();

            CodeNamespace lNamespace = new CodeNamespace("MyNamespace");
            lNamespace.Imports.Add(new CodeNamespaceImport("System"));
            lNamespace.Imports.Add(new CodeNamespaceImport("System.IO"));
            lUnit.Namespaces.Add(lNamespace);

            CodeTypeDeclaration lClass = new CodeTypeDeclaration("MyClass");
            CodeMethodInvokeExpression lExpression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("hello world !"));
            lNamespace.Types.Add(lClass);

            CodeEntryPointMethod lMain = new CodeEntryPointMethod();
            lMain.Statements.Add(lExpression);
            lClass.Members.Add(lMain);

            string lDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\";
            CodeGeneratorOptions lOptions = new CodeGeneratorOptions();
            lOptions.IndentString = "    ";
            lOptions.BlankLinesBetweenMembers = true;

            // generate a C# source code file
            CSharpCodeProvider lCSharpCodeProvider = new CSharpCodeProvider();
            using (StreamWriter lStreamWriter = new StreamWriter(lDesktopPath + "HelloWorld.cs", false))
            {
                lCSharpCodeProvider.GenerateCodeFromCompileUnit(lUnit, lStreamWriter, lOptions);
            }

            // generate a VB source code file
            VBCodeProvider lVBCodeProvider = new VBCodeProvider();
            using (StreamWriter lStreamWriter = new StreamWriter(lDesktopPath + "HelloWorld.vb", false))
            {
                lVBCodeProvider.GenerateCodeFromCompileUnit(lUnit, lStreamWriter, lOptions);
            }
        }
    }
}