C# / .NET - CodeDom.Compiler Set Assembly Info Attributes

僤鯓⒐⒋嵵緔 提交于 2020-07-03 10:18:46

问题


I am new to C# and am trying to use .NET's CodeDom.Compiler to compile an application and properly generate the assembly information in the outputted exe. I've been looking in the MS Docs / Class reference to do so. Is it possible to set the assembly information during compilation?

Code to compile my source code:

CompilerParameters CParams = new CompilerParameters();
CParams.GenerateExecutable = true;
CParams.OutputAssembly = Output;

string options = "/optimize+ /platform:x86 /target:winexe /unsafe";
if (Icon != null)
    options += " /win32icon:\"" + Icon + "\"";

CParams.CompilerOptions = options;
CParams.TreatWarningsAsErrors = false;
CParams.ReferencedAssemblies.Add("System.dll");
CParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CParams.ReferencedAssemblies.Add("System.Drawing.dll");
CParams.ReferencedAssemblies.Add("System.Data.dll");
CParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");

Dictionary<string, string> ProviderOptions = new Dictionary<string, string>();
ProviderOptions.Add("CompilerVersion", "v2.0");

CompilerResults Results = new CSharpCodeProvider(ProviderOptions).CompileAssemblyFromSource(CParams, source);

Outputted Exe's Assembly Information:

Is this function available when I'm actually saving the exe using the Writer?

Writer.WriteResource(FSave.FileName, EncryptedBytes);

I greatly appreciate any leads, thank you.


回答1:


Instead your last line

        ...
        var unit = new CodeCompileUnit();
        var attr = new CodeTypeReference(typeof(AssemblyVersionAttribute));
        var decl = new CodeAttributeDeclaration(attr, new CodeAttributeArgument(new CodePrimitiveExpression("1.0.2.42")));
        unit.AssemblyCustomAttributes.Add(decl);
        var prov = new CSharpCodeProvider(ProviderOptions);
        var assemblyInfo = new StringWriter();
        prov.GenerateCodeFromCompileUnit(unit, assemblyInfo, new CodeGeneratorOptions());

        var result = prov.CompileAssemblyFromSource(CParams, new[] {"public class p{public static void Main(){}}", assemblyInfo.ToString()});

generate assemblyinfo and add this to source for compilation

msdn



来源:https://stackoverflow.com/questions/52542250/c-sharp-net-codedom-compiler-set-assembly-info-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!