如何获取正在执行的程序集版本?

问题描述 投票:0回答:7

我正在尝试使用以下代码获取 C# 3.0 中的执行程序集版本:

var assemblyFullName = Assembly.GetExecutingAssembly().FullName;
var version = assemblyFullName .Split(',')[1].Split('=')[1];

还有其他正确的方法吗?

c# .net .net-assembly
7个回答
369
投票

两个选项...无论应用程序类型如何,您都可以随时调用:

Assembly.GetExecutingAssembly().GetName().Version

如果是Windows Forms应用程序,如果专门寻找产品版本,您始终可以通过应用程序访问。

Application.ProductVersion

使用

GetExecutingAssembly
作为装配参考并不总是一种选择。因此,我个人发现在可能需要引用底层程序集或程序集版本的项目中创建静态帮助程序类很有用:

// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
    public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
    public static readonly Version Version = Reference.GetName().Version;
}

然后我可以根据需要在我的代码中干净地引用

CoreAssembly.Version


46
投票

在 MSDN 中,Assembly.GetExecutingAssembly 方法,是关于方法“getexecutingassemble”的注释,出于性能原因,仅当您在设计时不知道当前正在执行什么程序集时才应调用此方法。

检索表示当前程序集的 Assembly 对象的推荐方法是使用程序集中找到的类型的

Type.Assembly
属性。

以下示例说明:

using System;
using System.Reflection;

public class Example
{
    public static void Main()
    {
        Console.WriteLine("The version of the currently executing assembly is: {0}",
                          typeof(Example).Assembly.GetName().Version);
    }
}

/* This example produces output similar to the following:
   The version of the currently executing assembly is: 1.1.0.0

当然,这与辅助类“public static class CoreAssembly”的答案非常相似,但是,如果您至少知道一种执行程序集的类型,则不必创建辅助类,并且可以节省您的时间。


23
投票
using System.Reflection;
{
    string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}

来自 MSDN 的评论 http://msdn.microsoft.com/en-us/library/system.reflection. assembly.getentry assembly%28v=vs.110%29.aspx:

当从非托管应用程序加载托管程序集时,

GetEntryAssembly
方法可以返回
null
。例如,如果非托管应用程序创建用 C# 编写的 COM 组件的实例,则从 C# 组件调用
GetEntryAssembly
方法将返回
null
,因为进程的入口点是非托管代码而不是托管程序集.


11
投票
如果您通过 GitVersion 或其他版本控制软件使用版本控制,则

Product Version
可能是首选。

要从类库中获取此内容,您可以致电

System.Diagnostics.FileVersionInfo.ProductVersion
:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here


7
投票

这应该做:

Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();

4
投票

我最终选择了

typeof(MyClass).GetTypeInfo().Assembly.GetName().Version
作为 netstandard1.6 应用程序。所有其他提出的答案都提供了部分解决方案。这是唯一能让我得到我所需要的东西。

源自多个地点:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx


0
投票

这似乎适用于 Git 版本控制

Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version
© www.soinside.com 2019 - 2024. All rights reserved.