Export (0) Print
Expand All
1 out of 3 rated this helpful - Rate this topic

CSharpCodeProvider Class

Provides access to instances of the C# code generator and code compiler.

Namespace:  Microsoft.CSharp
Assembly:  System (in System.dll)
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public class CSharpCodeProvider : CodeDomProvider

The CSharpCodeProvider type exposes the following members.

  NameDescription
Public methodCSharpCodeProvider()Initializes a new instance of the CSharpCodeProvider class.
Public methodCSharpCodeProvider(IDictionary<String, String>)Initializes a new instance of the CSharpCodeProvider class by using the specified provider options.
Top
  NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyFileExtensionGets the file name extension to use when creating source code files. (Overrides CodeDomProvider.FileExtension.)
Public propertyLanguageOptionsGets a language features identifier. (Inherited from CodeDomProvider.)
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Top
  NameDescription
Public methodCompileAssemblyFromDomCompiles an assembly based on the System.CodeDom trees contained in the specified array of CodeCompileUnit objects, using the specified compiler settings. (Inherited from CodeDomProvider.)
Public methodCompileAssemblyFromFileCompiles an assembly from the source code contained in the specified files, using the specified compiler settings. (Inherited from CodeDomProvider.)
Public methodCompileAssemblyFromSourceCompiles an assembly from the specified array of strings containing source code, using the specified compiler settings. (Inherited from CodeDomProvider.)
Public methodCreateCompiler Obsolete. Gets an instance of the C# code compiler. (Overrides CodeDomProvider.CreateCompiler().)
Public methodCreateEscapedIdentifierCreates an escaped identifier for the specified value. (Inherited from CodeDomProvider.)
Public methodCreateGenerator() Obsolete. Gets an instance of the C# code generator. (Overrides CodeDomProvider.CreateGenerator().)
Public methodCreateGenerator(String)When overridden in a derived class, creates a new code generator using the specified file name for output. (Inherited from CodeDomProvider.)
Public methodCreateGenerator(TextWriter)When overridden in a derived class, creates a new code generator using the specified TextWriter for output. (Inherited from CodeDomProvider.)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodCreateParser Obsolete. When overridden in a derived class, creates a new code parser. (Inherited from CodeDomProvider.)
Public methodCreateValidIdentifierCreates a valid identifier for the specified value. (Inherited from CodeDomProvider.)
Public methodDispose()Releases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGenerateCodeFromCompileUnitGenerates code for the specified Code Document Object Model (CodeDOM) compilation unit and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.)
Public methodGenerateCodeFromExpressionGenerates code for the specified Code Document Object Model (CodeDOM) expression and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.)
Public methodGenerateCodeFromMemberGenerates code for the specified class member using the specified text writer and code generator options. (Overrides CodeDomProvider.GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions).)
Public methodGenerateCodeFromNamespaceGenerates code for the specified Code Document Object Model (CodeDOM) namespace and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.)
Public methodGenerateCodeFromStatementGenerates code for the specified Code Document Object Model (CodeDOM) statement and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.)
Public methodGenerateCodeFromTypeGenerates code for the specified Code Document Object Model (CodeDOM) type declaration and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.)
Public methodGetConverterGets a TypeConverter for the specified type of object. (Overrides CodeDomProvider.GetConverter(Type).)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetTypeOutputGets the type indicated by the specified CodeTypeReference. (Inherited from CodeDomProvider.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodIsValidIdentifierReturns a value that indicates whether the specified value is a valid identifier for the current language. (Inherited from CodeDomProvider.)
Protected methodMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodParseCompiles the code read from the specified text stream into a CodeCompileUnit. (Inherited from CodeDomProvider.)
Public methodSupportsReturns a value indicating whether the specified code generation support is provided. (Inherited from CodeDomProvider.)
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top
  NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Top

This class provides methods that can be used to retrieve instances of the C# ICodeGenerator and ICodeCompiler implementations.

NoteNote

This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands and Inheritance Demands.

The following example uses either the C# or Visual Basic code provider to compile a source file. The example checks the input file extension and uses the corresponding CSharpCodeProvider or VBCodeProvider for compilation. The input file is compiled into an executable file, and any compilation errors are displayed to the console.

using System;
using System.IO;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Text;
using Microsoft.CSharp;
using Microsoft.VisualBasic;

namespace CodeProviders
{
	class CompileSample
	{
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                //  First parameter is the source file name. 
                if (File.Exists(args[0]))
                {
                    CompileExecutable(args[0]);
                }
                else 
                {
                    Console.WriteLine("Input source file not found - {0}",
                        args[0]);
                }
            }
            else 
            {
                Console.WriteLine("Input source file not specified on command line!");
            }
        }

        public static bool CompileExecutable(String sourceName)
        {
            FileInfo sourceFile = new FileInfo(sourceName);
            CodeDomProvider provider = null;
            bool compileOk = false;

            // Select the code provider based on the input file extension. 
            if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
            {
                provider = CodeDomProvider.CreateProvider("CSharp");
            }
            else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB")
            {
                provider = CodeDomProvider.CreateProvider("VisualBasic");
            }
            else 
            {
                Console.WriteLine("Source file must have a .cs or .vb extension");
            }

            if (provider != null)
            {

                // Format the executable file name. 
                // Build the output assembly path using the current directory 
                // and <source>_cs.exe or <source>_vb.exe.

                String exeName = String.Format(@"{0}\{1}.exe", 
                    System.Environment.CurrentDirectory, 
                    sourceFile.Name.Replace(".", "_"));

                CompilerParameters cp = new CompilerParameters();

                // Generate an executable instead of  
                // a class library.
                cp.GenerateExecutable = true;

                // Specify the assembly file name to generate.
                cp.OutputAssembly = exeName;

                // Save the assembly as a physical file.
                cp.GenerateInMemory = false;

                // Set whether to treat all warnings as errors.
                cp.TreatWarningsAsErrors = false;

                // Invoke compilation of the source file.
                CompilerResults cr = provider.CompileAssemblyFromFile(cp, 
                    sourceName);

                if(cr.Errors.Count > 0)
                {
                    // Display compilation errors.
                    Console.WriteLine("Errors building {0} into {1}",  
                        sourceName, cr.PathToAssembly);
                    foreach(CompilerError ce in cr.Errors)
                    {
                        Console.WriteLine("  {0}", ce.ToString());
                        Console.WriteLine();
                    }
                }
                else
                {
                    // Display a successful compilation message.
                    Console.WriteLine("Source {0} built into {1} successfully.",
                        sourceName, cr.PathToAssembly);
                }

                // Return the results of the compilation. 
                if (cr.Errors.Count > 0)
                {
                    compileOk = false;
                }
                else 
                {
                    compileOk = true;
                }
            }
            return compileOk;
        }
	}
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.