C#动态编译
公司需要自己做一个打包程序,将需要升级文件和脚本做成一个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" };
// CompileAssemblyFromSource表示根据代码进行编译(而不是文件) 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...");
有了核心代码,后面的就可以自己去实现文件的加入和提取了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
2016-05-16 如何很好的使用Linq的Distinct方法