C#/.NET - CodeDom.Compiler 设置程序集信息属性

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

我是 C# 新手,正在尝试使用 .NET CodeDom.Compiler 编译应用程序并在输出的 exe 中正确生成程序集信息。我一直在寻找 MS Docs / Class 参考来这样做。是否可以在编译时设置汇编信息?

编译我的源代码的代码:

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

输出的exe的汇编信息:

我在用Writer实际保存exe时可以使用这个功能吗?

Writer.WriteResource(FSave.FileName, EncryptedBytes);

非常感谢任何线索,谢谢。

而不是你的最后一行

        ...
        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()});

生成 assemblyinfo 并将其添加到源代码中进行编译

msdn