Editar

Partilhar via


CSharpCodeProvider Class

Definition

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

public ref class CSharpCodeProvider : System::CodeDom::Compiler::CodeDomProvider
public class CSharpCodeProvider : System.CodeDom.Compiler.CodeDomProvider
type CSharpCodeProvider = class
    inherit CodeDomProvider
Public Class CSharpCodeProvider
Inherits CodeDomProvider
Inheritance

Examples

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.

Important

The CompileAssemblyFrom* methods aren't supported on .NET Core and .NET 5+. This example only runs on .NET Framework.

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;
        }
    }
}
Imports System.IO
Imports System.Globalization
Imports System.CodeDom.Compiler
Imports System.Text
Imports Microsoft.CSharp

Namespace CodeProviders
    Class CompileSample
        <STAThread()>  _
        Public Shared Sub Main(args() As String)

            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))
                End If
            
            Else
                Console.WriteLine("Input source file not specified on command line!")
            End If
        End Sub

        Public Shared Function CompileExecutable(sourceName As String) As Boolean
            Dim sourceFile As FileInfo = New FileInfo(sourceName)
            Dim provider As CodeDomProvider = Nothing
            Dim compileOk As Boolean = False

            ' Select the code provider based on the input file extension.
            If sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".CS"

                provider = CodeDomProvider.CreateProvider("CSharp")

            ElseIf sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".VB"

                provider = CodeDomProvider.CreateProvider("VisualBasic")

            Else
                Console.WriteLine("Source file must have a .cs or .vb extension")
            End If

            If Not provider Is Nothing

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

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

                Dim cp As CompilerParameters = 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.
                Dim cr As CompilerResults = provider.CompileAssemblyFromFile(cp, _
                    sourceName)
    
                If cr.Errors.Count > 0
                    ' Display compilation errors.
                    Console.WriteLine("Errors building {0} into {1}", _
                        sourceName, cr.PathToAssembly)

                    Dim ce As CompilerError
                    For Each ce In cr.Errors
                        Console.WriteLine("  {0}", ce.ToString())
                        Console.WriteLine()
                    Next ce
                Else
                    ' Display a successful compilation message.
                    Console.WriteLine("Source {0} built into {1} successfully.", _
                        sourceName, cr.PathToAssembly)
                End If
              
                ' Return the results of the compilation.
                If cr.Errors.Count > 0
                    compileOk = False
                Else 
                    compileOk = True
                End If
            End If
            return compileOk

        End Function
    End Class
End Namespace

Remarks

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

Note

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.

Constructors

CSharpCodeProvider()

Initializes a new instance of the CSharpCodeProvider class.

CSharpCodeProvider(IDictionary<String,String>)

Initializes a new instance of the CSharpCodeProvider class by using the specified provider options.

Properties

CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container

Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
FileExtension

Gets the file name extension to use when creating source code files.

LanguageOptions

Gets a language features identifier.

(Inherited from CodeDomProvider)
Site

Gets or sets the ISite of the Component.

(Inherited from Component)

Methods

CompileAssemblyFromDom(CompilerParameters, CodeCompileUnit[])

Compiles an assembly based on the System.CodeDom trees contained in the specified array of CodeCompileUnit objects, using the specified compiler settings.

(Inherited from CodeDomProvider)
CompileAssemblyFromFile(CompilerParameters, String[])

Compiles an assembly from the source code contained in the specified files, using the specified compiler settings.

(Inherited from CodeDomProvider)
CompileAssemblyFromSource(CompilerParameters, String[])

Compiles an assembly from the specified array of strings containing source code, using the specified compiler settings.

(Inherited from CodeDomProvider)
CreateCompiler()
Obsolete.
Obsolete.

Gets an instance of the C# code compiler.

CreateEscapedIdentifier(String)

Creates an escaped identifier for the specified value.

(Inherited from CodeDomProvider)
CreateGenerator()
Obsolete.
Obsolete.

Gets an instance of the C# code generator.

CreateGenerator(String)

When overridden in a derived class, creates a new code generator using the specified file name for output.

(Inherited from CodeDomProvider)
CreateGenerator(TextWriter)

When overridden in a derived class, creates a new code generator using the specified TextWriter for output.

(Inherited from CodeDomProvider)
CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateParser()
Obsolete.
Obsolete.

When overridden in a derived class, creates a new code parser.

(Inherited from CodeDomProvider)
CreateValidIdentifier(String)

Creates a valid identifier for the specified value.

(Inherited from CodeDomProvider)
Dispose()

Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GenerateCodeFromCompileUnit(CodeCompileUnit, TextWriter, CodeGeneratorOptions)

Generates 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)
GenerateCodeFromExpression(CodeExpression, TextWriter, CodeGeneratorOptions)

Generates 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)
GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions)

Generates code for the specified class member using the specified text writer and code generator options.

GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions)

Generates code for the specified Code Document Object Model (CodeDOM) member declaration and sends it to the specified text writer, using the specified options.

(Inherited from CodeDomProvider)
GenerateCodeFromNamespace(CodeNamespace, TextWriter, CodeGeneratorOptions)

Generates 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)
GenerateCodeFromStatement(CodeStatement, TextWriter, CodeGeneratorOptions)

Generates 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)
GenerateCodeFromType(CodeTypeDeclaration, TextWriter, CodeGeneratorOptions)

Generates 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)
GetConverter(Type)

Gets a TypeConverter for the specified type of object.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetTypeOutput(CodeTypeReference)

Gets the type indicated by the specified CodeTypeReference.

(Inherited from CodeDomProvider)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
IsValidIdentifier(String)

Returns a value that indicates whether the specified value is a valid identifier for the current language.

(Inherited from CodeDomProvider)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Parse(TextReader)

Compiles the code read from the specified text stream into a CodeCompileUnit.

(Inherited from CodeDomProvider)
Supports(GeneratorSupport)

Returns a value indicating whether the specified code generation support is provided.

(Inherited from CodeDomProvider)
ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component)

Events

Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

Applies to

See also