ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C#动态编译

2019-05-16 13:50:17  阅读:246  来源: 互联网

标签:文件 exe Console .. C# 编译 myFile 动态 options


公司需要自己做一个打包程序,将需要升级文件和脚本做成一个exe安装包,双击exe安装包的时候输入相关的参数就执行升级(文件覆盖和脚本执行),大概思路如下:
1.先把exe的逻辑写好,包括提取文件和脚本执行代码
2.exe从资源中提取文件和脚本
3.组包程序将需要升级的脚本和文件加入到exe的资源文件,然后编译成exe。

exe的核心代码如下:

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);


组包的核心代码如下:

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...");

 

有了核心代码,后面的就可以自己去实现文件的加入和提取了。

标签:文件,exe,Console,..,C#,编译,myFile,动态,options
来源: https://www.cnblogs.com/duanjt/p/10875163.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有