C#動態編譯

公司須要本身作一個打包程序,將須要升級文件和腳本作成一個exe安裝包,雙擊exe安裝包的時候輸入相關的參數就執行升級(文件覆蓋和腳本執行),大概思路以下:
1.先把exe的邏輯寫好,包括提取文件和腳本執行代碼
2.exe從資源中提取文件和腳本
3.組包程序將須要升級的腳本和文件加入到exe的資源文件,而後編譯成exe。ide

exe的核心代碼以下:this

if (!Directory.Exists("myFile"))
{
    Directory.CreateDirectory("myFile");
}

//獲取資源文件並輸出到myFile文件夾
Assembly assm = Assembly.GetExecutingAssembly();
foreach (var item in assm.GetManifestResourceNames())
{
    Stream stream = assm.GetManifestResourceStream(item);
    byte[] bs = new byte[stream.Length];
    stream.Read(bs, 0, bs.Length);
    File.WriteAllBytes("myFile\\" + item, bs);
    this.textBox1.AppendText("成功提取文件:" + item + "\r\n");
}
this.textBox1.AppendText("文件保存在:"+AppDomain.CurrentDomain.BaseDirectory+"\\myFile");
string result = string.Join("*", assm.GetManifestResourceNames());
MessageBox.Show("成功," + result);


組包的核心代碼以下:spa

CSharpCodeProvider p = new CSharpCodeProvider();

// 設置編譯參數
CompilerParameters options = new CompilerParameters();

//加入引用的程序集
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.Windows.Forms.dll");
options.ReferencedAssemblies.Add("System.Drawing.dll");

options.GenerateExecutable = true;                  //是否生成可執行文件,不然就是內存中
// CompilerOptions 參考地址:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/compiler-options/addmodule-compiler-option
options.CompilerOptions = "-t:winexe";              //非控制檯應用程序
options.CompilerOptions += " -win32icon:index.ico"; //設置圖標
options.OutputAssembly = "HelloWorld.exe";          //輸出exe的名稱
options.MainClass = "TestPackage.Program";          //主運行類

//循環加入資源文件,貌似不支持文件夾,所以多個文件能夠本身壓縮爲zip再加入
foreach (var file in this.listBox1.Items)
{
    options.EmbeddedResources.Add(file.ToString());
}

// 開始編譯
string[] files = new string[]{
    @"..\..\..\TestPackage\Program.cs",
    @"..\..\..\TestPackage\MainForm.cs"
};
CompilerResults cr = p.CompileAssemblyFromFile(options, files);

// 顯示編譯信息
if (cr.Errors.Count == 0)
{
    Console.WriteLine("{0} compiled ok!", cr.CompiledAssembly.Location);
    MessageBox.Show("成功");
}
else
{
    Console.WriteLine("Complie Error:");
    foreach (CompilerError error in cr.Errors)
        Console.WriteLine("  {0}", error);
    MessageBox.Show("失敗");
}

Console.WriteLine("Press Enter key to exit...");

 

有了核心代碼,後面的就能夠本身去實現文件的加入和提取了。code

相關文章
相關標籤/搜索