Programmatically change the AssemblyVersion and AssemblyFileVersion attributes

元气小坏坏 提交于 2019-11-28 11:19:21

Why don't you, during build process, read the AssemblyVersion and AssemblyFileVersion of one DLL, and save it back to other csproject's AssemblyInfo.cs, only then compile it?

As a matter of fact, I don't know whether it is possible to modify the DLL file directly, without resorting to something fanciful.

Or alternatively, make sure that all your DLLs share one common AssemblyInfo.cs. You can do this by adding the AssemblyInfo.cs as "Add As Link" when you add a new item in csproject. In this way when you do a compilation, all the DLLs will share the same AssemblyInfo.cs, and thus output the same AssemblyVersion.

In my case, I created a T4 template for changing the AssemblyVersion and AssemblyFileVersion. I called the template Assembly.tt, and made it a linked file (when you add it choose Add Link, instead of Add). All my assemblies pull in the linked Assembly.tt file.

You can then run the T4 template from one location and it will update all the AssemblyVersion and AssemblyFileVersions. You don't have to call the file AssemblyInfo.cs for the information to be pulled into your dlls.

The code for the Assembly.tt file is:

<#@ template language="C#" hostspecific="true" #>
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("4.<#= this.RevisionYear #>.<#= this.RevisionNumber #>.<#= this.RevisionTime #>")]
[assembly: AssemblyFileVersion("4.<#= this.RevisionYear #>.<#= this.RevisionNumber #>.<#= this.RevisionTime #>")]
<#+
    int RevisionYear = DateTime.UtcNow.Year;
    int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(DateTime.UtcNow.Year,1,1)).TotalDays;
    int RevisionTime = (int)(DateTime.UtcNow - new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day)).TotalMinutes;
#>

The output of the T4 template above will be:

// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// 

using System.Reflection;

[assembly: AssemblyVersion("4.2016.284.1066")]
[assembly: AssemblyFileVersion("4.2016.284.1066")]
The Chairman

If you have access to the sources, take the advice from Graviton

If you don't, you might be in trouble. Possibly you can disassemble with ILDASM and reassemble with ILASM. But this won't work out for strong-named assemblies.

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