| public bool CompileScripts(string assemblyName, string path, bool debug) { | |
| 92 | |
| 93 | // find all CSharp files |
| 94 | // TODO: Make compilation more generic |
| 95 | string[] scriptFiles = Directory.GetFiles(path, "*.cs"); |
| 96 | |
| 97 | // create a code compiler |
| 98 | CSharpCodeProvider provider = new CSharpCodeProvider(); |
| 99 | |
| 100 | // configure params for the script compilation |
| 101 | CompilerParameters parms = new CompilerParameters(dynamicAssemblyRefs); |
| 102 | |
| 103 | // this is an in memory assembly |
| 104 | // TODO: Consider compiling to file and loading if no changes have occurred on the next load |
| 105 | parms.GenerateInMemory = true; |
| 106 | parms.GenerateExecutable = false; |
| 107 | parms.IncludeDebugInformation = debug; |
| 108 | |
| 109 | // compile the list of files found in the script directory |
| 110 | CompilerResults results = provider.CompileAssemblyFromFile(parms, scriptFiles); |
| 111 | |
| 112 | // check for errors and log them |
| 113 | if(results.Errors.Count != 0) { |
| 114 | StringBuilder errorBuilder = new StringBuilder(results.Errors.Count); |
| 115 | |
| 116 | string errorMsg = "Script Error [File: {0}, Line: {1}]: {2}]" + Environment.NewLine; |
| 117 | |
| 118 | foreach(CompilerError error in results.Errors) { |
| 119 | errorBuilder.AppendFormat(errorMsg, error.FileName, error.Line, error.ErrorText); |
| 120 | } |
| 121 | |
| 122 | Logger.Instance.LogEvent(errorBuilder.ToString(), LoggingLevel.Errors); |
| 123 | |
| 124 | return false; |
| 125 | } |
| 126 | |
| 127 | AttachAssembly(results.CompiledAssembly); |
| 128 | |
| 129 | // success |
| 130 | return true; |
| 131 | } |
动态编译c#
最新推荐文章于 2023-05-25 10:27:16 发布
本文介绍了一个用于C#脚本编译及错误处理的通用方法,包括查找所有C#文件、配置编译参数、实现内存编译与错误日志记录。
1498

被折叠的 条评论
为什么被折叠?



