如何获取发布版本?

how to get publish version?

我想显示我的桌面应用程序的发布版本。我正在尝试使用以下代码来做到这一点:

_appVersion.Content = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

问题是我没有得到我在项目属性中的发布版本。下面是它的截图:

但我得到 3.0.0.12546。有人知道问题出在哪里吗?

We can create one property which will return the Version information as mention below and we can use that property.

public string VersionLabel
{
    get
    {
        if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
        {
            Version ver = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
            return string.Format("Product Name: {4}, Version: {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision, Assembly.GetEntryAssembly().GetName().Name);
        }
        else
        {
            var ver = Assembly.GetExecutingAssembly().GetName().Version;
            return string.Format("Product Name: {4}, Version: {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision, Assembly.GetEntryAssembly().GetName().Name);
        }
    }
}

我也遇到了这个问题,发现 AssemblyInfo.cs 中设置的版本号干扰了 Properties 中设置的版本号:

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

我通常将 AssemblyInfo 中的那些行注释掉并替换为

[assembly: AssemblyVersion("1.0.*")]

检查这些值是否已硬编码到您的 AssemblyInfo 文件中。

有关自动版本控制的有趣讨论,请参阅 this SO question。检查 AssemblyInfo.cs 时,请确保您的自动增量(* - 如果您正在使用它)仅针对 AssemblyVersion 而不是 AssemblyFileVersion


调试程序时,可以在

中查看程序集的属性
\bin\Release\app.publish

Details 选项卡下,检查版本号。这是否与您在 VS 中指定的任何设置匹配?

System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

将为您提供存在于 AssemblyInfo.cs 文件中的程序集版本,要获取您在发布对话框中设置的发布版本,您应该使用

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion

但请注意,您必须添加对 System.Deployment 的引用,并且只有在您通过右键单击项目文件并单击发布来发布您的应用程序后,它才会起作用,每次发布时,它都会增加 Revision .

如果您试图在调试模式下调用上面的行,它将不起作用并且会抛出异常,因此您可以使用以下代码:

try
{
    return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
catch(Exception ex)
{
    return Assembly.GetExecutingAssembly().GetName().Version;
}

使用 C# 6.0 和 Lambda 表达式

private string GetVersion => ApplicationDeployment.IsNetworkDeployed ? $"Version: {ApplicationDeployment.CurrentDeployment.CurrentVersion}" : $"Version: {Application.ProductVersion}";