CSharpCodeProvider 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
提供 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 的 or 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 。
建構函式
| 名稱 | Description |
|---|---|
| CSharpCodeProvider() |
初始化 CSharpCodeProvider 類別的新執行個體。 |
| CSharpCodeProvider(IDictionary<String,String>) |
透過使用指定的提供者選項初始化該類別的新 CSharpCodeProvider 實例。 |
屬性
| 名稱 | Description |
|---|---|
| CanRaiseEvents |
會得到一個值,表示該元件是否能引發事件。 (繼承來源 Component) |
| Container |
得到 IContainer 包含 Component的 。 (繼承來源 Component) |
| DesignMode |
會得到一個值,表示目前 Component 是否處於設計模式。 (繼承來源 Component) |
| Events |
會取得與此 Component連結的事件處理程序清單。 (繼承來源 Component) |
| FileExtension |
取得檔案副檔名,用於建立原始碼檔案。 |
| LanguageOptions |
取得語言特徵識別碼。 (繼承來源 CodeDomProvider) |
| Site | (繼承來源 Component) |
方法
事件
| 名稱 | Description |
|---|---|
| Disposed |
當元件被呼叫方法 Dispose() 時會發生。 (繼承來源 Component) |