?? compilerunit.cs
字號:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;
namespace ProgramCalculator
{
/// <summary>
/// 編譯單元
/// </summary>
class CompilerUnit
{
/// <summary>
/// 獲取或設置 編譯函數代碼時引用的程序集的完整路徑的集合
/// </summary>
public static StringCollection ReferenceAssemblyCollection = new StringCollection();
private static ICodeCompiler compiler = (new CSharpCodeProvider()).CreateCompiler();
/// <summary>
/// 編譯
/// </summary>
/// <param name="source">源代碼</param>
/// <param name="makeExe">是否生成可執行程序</param>
/// <param name="inMemory">是否在內存中生成,(如果true請將 outputAssembly設置為null)</param>
/// <param name="dlls">加載的dll的完整路徑</param>
/// <param name="outputAssembly">輸出程序集的完整路徑(如果inMemory參數為true則請使用null)</param>
public static CompilerResults Compile(string source, bool makeExe,bool inMemory,string[] dlls, string outputAssembly)
{
CompilerParameters parameters = new CompilerParameters();
//加載dll
if (dlls != null)
{
parameters.ReferencedAssemblies.AddRange(dlls);
}
parameters.GenerateExecutable = makeExe;
parameters.GenerateInMemory = inMemory;
if (!inMemory)
{
parameters.OutputAssembly = outputAssembly;
}
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);
return results;
}
/// <summary>
/// 生成函數dll
/// </summary>
/// <param name="compileRes">CompilerResult對象</param>
/// <returns>成功返回true</returns>
public static bool BuildFunctionDll(out CompilerResults compileRes)
{
//----------------------------------
//獲取源代碼source
//是所有代碼相關文件(.us,.ch,.cf,.ct)的組合
//----------------------------------
string source = "";
source += CompilerUnit.ReadFile(Function.GetPathOfUsingFile()) +
CompilerUnit.ReadFile(Function.GetPathOfClassHeaderFile());
DirectoryInfo dir = new DirectoryInfo(Function.DirectoryOfFunctions);
FileInfo[] functionFiles = dir.GetFiles("*.cf");
foreach (FileInfo file in functionFiles)
{
source += ReadFile(file.FullName);
}
source += CompilerUnit.ReadFile(Function.GetPathOfClassTailFile());
//添加引用
string[] dlls = new string[CompilerUnit.ReferenceAssemblyCollection.Count];
CompilerUnit.ReferenceAssemblyCollection.CopyTo(dlls, 0);
//輸出路徑
string output = Function.GetPathOfNewFunctionDll();
compileRes = CompilerUnit.Compile(source, false, false, dlls, output);
//如果成功生成
if (compileRes.Errors.Count == 0)
{
return true;
}
return false;
}
public static string ReadFile(string path)
{
StreamReader sw = new StreamReader(path);
try
{
return sw.ReadToEnd();
}
catch
{
}
finally
{
sw.Close();
}
return "";
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -