CSharpCodeProvider クラス

定義

C# コード ジェネレーターとコード コンパイラのインスタンスへのアクセスを提供します。

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
継承

次の例では、C# または Visual Basic コード プロバイダーを使用してソース ファイルをコンパイルします。 この例では、入力ファイル拡張子を確認し、対応する CSharpCodeProvider または VBCodeProvider を使用してコンパイルします。 入力ファイルは実行可能ファイルにコンパイルされ、コンパイル エラーがコンソールに表示されます。

Important

CompileAssemblyFrom* メソッドは、.NET Core および .NET 5 以降ではサポートされていません。 この例は、.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

注釈

このクラスは、C# ICodeGenerator および ICodeCompiler 実装のインスタンスを取得するために使用できるメソッドを提供します。

Note

このクラスには、すべてのメンバーに適用されるクラス レベルでのリンク要求と継承要求が含まれます。 直接の呼び出し元か派生クラスのいずれかに完全信頼アクセス許可がない場合、SecurityException がスローされます。

コンストラクター

名前 説明
CSharpCodeProvider()

CSharpCodeProvider クラスの新しいインスタンスを初期化します。

CSharpCodeProvider(IDictionary<String,String>)

指定したプロバイダー オプションを使用して、 CSharpCodeProvider クラスの新しいインスタンスを初期化します。

プロパティ

名前 説明
CanRaiseEvents

コンポーネントがイベントを発生できるかどうかを示す値を取得します。

(継承元 Component)
Container

IContainerを含むComponentを取得します。

(継承元 Component)
DesignMode

Componentが現在デザイン モードであるかどうかを示す値を取得します。

(継承元 Component)
Events

この Componentにアタッチされているイベント ハンドラーの一覧を取得します。

(継承元 Component)
FileExtension

ソース コード ファイルの作成時に使用するファイル名拡張子を取得します。

LanguageOptions

言語機能識別子を取得します。

(継承元 CodeDomProvider)
Site

ISiteComponentを取得または設定します。

(継承元 Component)

メソッド

名前 説明
CompileAssemblyFromDom(CompilerParameters, CodeCompileUnit[])

指定したコンパイラ設定を使用して、System.CodeDom オブジェクトの指定した配列に含まれるCodeCompileUnit ツリーに基づいてアセンブリをコンパイルします。

(継承元 CodeDomProvider)
CompileAssemblyFromFile(CompilerParameters, String[])

指定したコンパイラ設定を使用して、指定したファイルに含まれるソース コードからアセンブリをコンパイルします。

(継承元 CodeDomProvider)
CompileAssemblyFromSource(CompilerParameters, String[])

指定したコンパイラ設定を使用して、ソース コードを含む文字列の指定した配列からアセンブリをコンパイルします。

(継承元 CodeDomProvider)
CreateCompiler()
古い.

C# コード コンパイラのインスタンスを取得します。

CreateEscapedIdentifier(String)

指定した値のエスケープされた識別子を作成します。

(継承元 CodeDomProvider)
CreateGenerator()
古い.

C# コード ジェネレーターのインスタンスを取得します。

CreateGenerator(String)

派生クラスでオーバーライドされた場合は、指定したファイル名を使用して出力用に新しいコード ジェネレーターを作成します。

(継承元 CodeDomProvider)
CreateGenerator(TextWriter)

派生クラスでオーバーライドされた場合は、出力に指定した TextWriter を使用して新しいコード ジェネレーターを作成します。

(継承元 CodeDomProvider)
CreateObjRef(Type)

リモート オブジェクトとの通信に使用されるプロキシの生成に必要なすべての関連情報を含むオブジェクトを作成します。

(継承元 MarshalByRefObject)
CreateParser()
古い.

派生クラスでオーバーライドされた場合は、新しいコード パーサーを作成します。

(継承元 CodeDomProvider)
CreateValidIdentifier(String)

指定した値の有効な識別子を作成します。

(継承元 CodeDomProvider)
Dispose()

Componentによって使用されるすべてのリソースを解放します。

(継承元 Component)
Dispose(Boolean)

Componentによって使用されるアンマネージ リソースを解放し、必要に応じてマネージド リソースを解放します。

(継承元 Component)
Equals(Object)

指定したオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GenerateCodeFromCompileUnit(CodeCompileUnit, TextWriter, CodeGeneratorOptions)

指定したコード ドキュメント オブジェクト モデル (CodeDOM) コンパイル ユニットのコードを生成し、指定したオプションを使用して、指定したテキスト ライターに送信します。

(継承元 CodeDomProvider)
GenerateCodeFromExpression(CodeExpression, TextWriter, CodeGeneratorOptions)

指定したコード ドキュメント オブジェクト モデル (CodeDOM) 式のコードを生成し、指定したオプションを使用して、指定したテキスト ライターに送信します。

(継承元 CodeDomProvider)
GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions)

指定したテキスト ライターおよびコード ジェネレーター オプションを使用して、指定したクラス メンバーのコードを生成します。

GenerateCodeFromNamespace(CodeNamespace, TextWriter, CodeGeneratorOptions)

指定したコード ドキュメント オブジェクト モデル (CodeDOM) 名前空間のコードを生成し、指定したオプションを使用して、指定したテキスト ライターに送信します。

(継承元 CodeDomProvider)
GenerateCodeFromStatement(CodeStatement, TextWriter, CodeGeneratorOptions)

指定したコード ドキュメント オブジェクト モデル (CodeDOM) ステートメントのコードを生成し、指定したオプションを使用して、指定したテキスト ライターに送信します。

(継承元 CodeDomProvider)
GenerateCodeFromType(CodeTypeDeclaration, TextWriter, CodeGeneratorOptions)

指定したコード ドキュメント オブジェクト モデル (CodeDOM) 型宣言のコードを生成し、指定したオプションを使用して、指定したテキスト ライターに送信します。

(継承元 CodeDomProvider)
GetConverter(Type)

指定した種類のオブジェクトの TypeConverter を取得します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()

このインスタンスの有効期間ポリシーを制御する現在の有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
GetService(Type)

ComponentまたはそのContainerによって提供されるサービスを表すオブジェクトを返します。

(継承元 Component)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
GetTypeOutput(CodeTypeReference)

指定した CodeTypeReferenceによって示される型を取得します。

(継承元 CodeDomProvider)
InitializeLifetimeService()

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
IsValidIdentifier(String)

指定した値が現在の言語の有効な識別子であるかどうかを示す値を返します。

(継承元 CodeDomProvider)
MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。

(継承元 MarshalByRefObject)
Parse(TextReader)

指定したテキスト ストリームから読み取ったコードを CodeCompileUnitにコンパイルします。

(継承元 CodeDomProvider)
Supports(GeneratorSupport)

指定したコード生成のサポートが提供されているかどうかを示す値を返します。

(継承元 CodeDomProvider)
ToString()

Stringの名前 (存在する場合) を含むComponentを返します。 このメソッドはオーバーライドしないでください。

(継承元 Component)

イベント

名前 説明
Disposed

コンポーネントが Dispose() メソッドの呼び出しによって破棄されるときに発生します。

(継承元 Component)

適用対象

こちらもご覧ください