如何手动设置程序集版本

5
这个问题让我很头疼。我们过去会将东西放在项目属性下的[assembly: AssemblyVersion("1.0.0.0")],我对变化非常适应,所以我不在意它在哪里。我知道他们正在采用新的版本标准,这也完全没问题。
许多文档指向project.json文件,但显然这已经不再是一个合法的文件了。最近的一些文档说要将以下内容添加到您的.csproj文件中:
<PropertyGroup>
    <VersionPrefix>1.2.3</VersionPrefix>
    <VersionSuffix>alpha</VersionSuffix>
</PropertyGroup>

这完全是浪费时间。只因为我似乎无法读取它。以下始终会给我1.0.0.0

PlatformServices.Default.Application.ApplicationVersion

更不用说当我在文件资源管理器中右键单击并点击“属性”,然后“详细信息”选项卡总是显示“1.0.0.0”。

那么,我该如何设置解决方案中每个程序集的版本,并在运行时读取它们呢?

2个回答

4

其中一种方法是在项目文件中设置以下任意一个值:

<PropertyGroup>
    <Version>1.3.5.7</Version>
    <FileVersion>2.4.6.8</FileVersion>
</PropertyGroup>

并像这样阅读它们:

var fileVersion = Assembly.GetEntryAssembly()
    .GetCustomAttribute<AssemblyFileVersionAttribute>()
    .Version;

var informationalVersion = Assembly.GetEntryAssembly()
    .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
    .InformationalVersion;

值得注意的是,在 .csproj 文件中设置这些值会自动生成一个类似于传统的 AssemblyInfo.cs 文件的文件(因此不要尝试编辑它),其中包含以下内容:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Reflection;

//snip    
[assembly: System.Reflection.AssemblyFileVersionAttribute("2.4.6.8")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.2.3")]

// Generated by the MSBuild WriteCodeFragment class.

你不需要新的属性组,只需将这些值与目标框架一起放入即可。 - DavidG
将版本移动到第一个“PropertyGroup”并没有改变任何内容。我理解您不想更改自动生成的文件,但是我甚至在重新生成后也找不到AssemblyInfo.cs文件。我一定是漏了什么? - Grandizer
自动生成的文件有点隐藏在 obj\Debug\netcoreapp1.1\YourProject.AssemblyInfo.cs 中。 - DavidG
我确实在那里看到了它,而且是1.0.0.0版本。这是netcoreapp2.0的问题吗? - Grandizer
不,这是1.1版本的事情。你能在项目属性中设置版本吗? - DavidG
显示剩余5条评论

0
原来这个问题在 .Net Core 2.0 发布后就解决了。当你右键点击项目,然后点击属性,就会出现下面的用户界面:

UI of Project Properties

Package VersionAssembly VersionAssembly File Version 对应于 .csproj 文件中的 VersionAssemblyVersionFileVersion 设置:

<PropertyGroup>
  <Version>1.1.0</Version>
  <AssemblyVersion>1.1.0.9</AssemblyVersion>
  <FileVersion>1.1.0.9</FileVersion>
</PropertyGroup>

然后我在解决方案的每个项目中创建了一个实用方法,执行以下操作:

public static VersionInformationModel GetVersionInformation() {
  var Result = new VersionInformationModel {
    Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
    BuildDate = System.IO.File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location),
    Configuration = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyConfigurationAttribute>().Configuration,
    TargetFramework = Assembly.GetExecutingAssembly().GetCustomAttribute<System.Runtime.Versioning.TargetFrameworkAttribute>().FrameworkName,
  };

  return Result;
}

在我的网站管理员页面上,我可以查看每个项目在任何服务器上的版本和其他详细信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接