我正在尝试使用以下代码在 C# 3.0 中获取执行程序集版本:
var assemblyFullName = Assembly.GetExecutingAssembly().FullName;
var version = assemblyFullName .Split(',')[1].Split('=')[1];
还有另一种正确的方法吗?
两个选项......无论应用程序类型如何,您都可以随时调用:
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
。
在 MSDN 中,Assembly.GetExecutingAssembly Method 是关于方法“getexecutingassembly”的注释,出于性能原因,只有在设计时不知道当前正在执行的程序集时才应调用此方法。
检索表示当前程序集的 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”的答案非常相似,但是,如果您知道至少一种执行程序集,则不必创建帮助类,这样可以节省您的时间。
using System.Reflection;
{
string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}
来自 MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx 的评论:
从非托管应用程序加载托管程序集时,GetEntryAssembly
方法可以返回 null
。例如,如果非托管应用程序创建用 C# 编写的 COM 组件的实例,则从 C# 组件调用 GetEntryAssembly
方法会返回 null
,因为进程的入口点是非托管代码而不是托管程序集.
GetEntryAssembly
(相对于 GetCallingAssembly
或 GetExecutingAssembly
)似乎是从参考库中调用时唯一有效的方法。
如果您通过 GitVersion 或其他版本控制软件使用版本控制,则可能首选 Product Version
。
要从您的类库中获取此信息,您可以调用 System.Diagnostics.FileVersionInfo.ProductVersion
:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
https://i.stack.imgur.com/Cio5P.png
这应该这样做:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
我最终选择了 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
System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion
ClickOnce
版本,它是在项目属性中的Publish
选项卡上指定的(即,与AssemblyVersion 或AssemblyFileVersion 无关)。HomeController
,因此在 Razor 中:v@(Assembly.GetAssembly(typeof(MyWebProject.Mvc.Controllers.HomeController)).GetName().Version.ToString(2))