CSharpCodeProvider 类  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
提供对 C# 代码生成器和代码编译器的实例的访问权限。
public ref class CSharpCodeProvider : System::CodeDom::Compiler::CodeDomProviderpublic class CSharpCodeProvider : System.CodeDom.Compiler.CodeDomProvidertype CSharpCodeProvider = class
    inherit CodeDomProviderPublic Class CSharpCodeProvider
Inherits CodeDomProvider- 继承
示例
以下示例使用 C# 或 Visual Basic 代码提供程序编译源文件。 该示例检查输入文件扩展名,并使用相应的 CSharpCodeProvider 或 VBCodeProvider 进行编译。 输入文件编译为可执行文件,任何编译错误都会显示在控制台中。
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
注解
此类提供可用于检索 C# ICodeGenerator 实例和 ICodeCompiler 实现的方法。
注意
此类包含应用于所有成员的类级别的链接需求和继承需求。 SecurityException当直接调用方或派生类没有完全信任权限时,将引发 。
构造函数
| CSharpCodeProvider() | 初始化 CSharpCodeProvider 类的新实例。 | 
| CSharpCodeProvider(IDictionary<String,String>) | 使用指定的提供程序选项初始化 CSharpCodeProvider 类的新实例。 | 
属性
| CanRaiseEvents | 获取一个指示组件是否可以引发事件的值。(继承自 Component) | 
| Container | 获取包含 IContainer 的 Component。(继承自 Component) | 
| DesignMode | 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自 Component) | 
| Events | 获取附加到此 Component 的事件处理程序的列表。(继承自 Component) | 
| FileExtension | 获取要在创建源代码文件时使用的文件扩展名。 | 
| LanguageOptions | 获取语言功能标识符。(继承自 CodeDomProvider) | 
| Site | (继承自 Component) | 
方法
事件
| Disposed | 在通过调用 Dispose() 方法释放组件时发生。(继承自 Component) |