C# 以编程方式获取 DLL 的版本号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1755504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:32:16  来源:igfitidea点击:

Programmatically get the version number of a DLL

c#.net

提问by JL.

Is it possible to get the version number programmatically from any .NET DLL?

是否可以从任何 .NET DLL 以编程方式获取版本号?

If yes, how?

如果是,如何?

采纳答案by Kris

Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Version ver = assembly.GetName().Version;

Important:It should be noted that this is not the best answer to the original question. Don't forget to read more on this page.

重要提示:应该注意,这不是原始问题的最佳答案。不要忘记在此页面上阅读更多内容。

回答by Ariel

You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.

您可以使用 System.Reflection.Assembly.Load*() 方法,然后获取它们的 AssemblyInfo。

回答by Agent_9191

To get it for the assembly that was started (winform, console app, etc...)

为已启动的程序集获取它(winform、控制台应用程序等...)

using System.Reflection;
...
Assembly.GetEntryAssembly().GetName().Version

回答by MacSpudster

Kris, your version works great when needing to load the assembly from the actual DLL file (and if the DLL is there!), however, one will get a much unwanted error if the DLL is EMBEDDED (i.e., not a file but an embedded DLL).

Kris,您的版本在需要从实际的 DLL 文件(如果 DLL 存在!)加载程序集时效果很好,但是,如果 DLL 是嵌入式的(即,不是文件而是嵌入式DLL)。

The other thing is, if one uses a versioning scheme with something like "1.2012.0508.0101", when one gets the version string you'll actually get "1.2012.518.101"; note the missing zeros.

另一件事是,如果有人使用类似“ 1.2012.0508.0101”的版本控制方案,当你得到版本字符串时,你实际上会得到“ 1.2012.518.101”;注意缺少的零

So, here's a few extra functions to get the version of a DLL (embedded or from the DLL file):

因此,这里有一些额外的函数来获取 DLL 的版本(嵌入的或来自 DLL 文件):

    public static System.Reflection.Assembly GetAssembly(string pAssemblyName)
    {
        System.Reflection.Assembly tMyAssembly = null;

        if (string.IsNullOrEmpty(pAssemblyName)) { return tMyAssembly; }
        tMyAssembly = GetAssemblyEmbedded(pAssemblyName);
        if (tMyAssembly == null) { GetAssemblyDLL(pAssemblyName); }

        return tMyAssembly;
    }//System.Reflection.Assembly GetAssemblyEmbedded(string pAssemblyDisplayName)


    public static System.Reflection.Assembly GetAssemblyEmbedded(string pAssemblyDisplayName)
    {
        System.Reflection.Assembly tMyAssembly = null;

        if(string.IsNullOrEmpty(pAssemblyDisplayName)) { return tMyAssembly; }
        try //try #a
        {
            tMyAssembly = System.Reflection.Assembly.Load(pAssemblyDisplayName);
        }// try #a
        catch (Exception ex)
        {
            string m = ex.Message;
        }// try #a
        return tMyAssembly;
    }//System.Reflection.Assembly GetAssemblyEmbedded(string pAssemblyDisplayName)


    public static System.Reflection.Assembly GetAssemblyDLL(string pAssemblyNameDLL)
    {
        System.Reflection.Assembly tMyAssembly = null;

        if (string.IsNullOrEmpty(pAssemblyNameDLL)) { return tMyAssembly; }
        try //try #a
        {
            if (!pAssemblyNameDLL.ToLower().EndsWith(".dll")) { pAssemblyNameDLL += ".dll"; }
            tMyAssembly = System.Reflection.Assembly.LoadFrom(pAssemblyNameDLL);
        }// try #a
        catch (Exception ex)
        {
            string m = ex.Message;
        }// try #a
        return tMyAssembly;
    }//System.Reflection.Assembly GetAssemblyFile(string pAssemblyNameDLL)


    public static string GetVersionStringFromAssembly(string pAssemblyDisplayName)
    {
        string tVersion = "Unknown";
        System.Reflection.Assembly tMyAssembly = null;

        tMyAssembly = GetAssembly(pAssemblyDisplayName);
        if (tMyAssembly == null) { return tVersion; }
        tVersion = GetVersionString(tMyAssembly.GetName().Version.ToString());
        return tVersion;
    }//string GetVersionStringFromAssemblyEmbedded(string pAssemblyDisplayName)


    public static string GetVersionString(Version pVersion)
    {
        string tVersion = "Unknown";
        if (pVersion == null) { return tVersion; }
        tVersion = GetVersionString(pVersion.ToString());
        return tVersion;
    }//string GetVersionString(Version pVersion)


    public static string GetVersionString(string pVersionString)
    {
        string tVersion = "Unknown";
        string[] aVersion;

        if (string.IsNullOrEmpty(pVersionString)) { return tVersion; }
        aVersion = pVersionString.Split('.');
        if (aVersion.Length > 0) { tVersion = aVersion[0]; }
        if (aVersion.Length > 1) { tVersion += "." + aVersion[1]; }
        if (aVersion.Length > 2) { tVersion += "." + aVersion[2].PadLeft(4, '0'); }
        if (aVersion.Length > 3) { tVersion += "." + aVersion[3].PadLeft(4, '0'); }

        return tVersion;
    }//string GetVersionString(Version pVersion)


    public static string GetVersionStringFromAssemblyEmbedded(string pAssemblyDisplayName)
    {
        string tVersion = "Unknown";
        System.Reflection.Assembly tMyAssembly = null;

        tMyAssembly = GetAssemblyEmbedded(pAssemblyDisplayName);
        if (tMyAssembly == null) { return tVersion; }
        tVersion = GetVersionString(tMyAssembly.GetName().Version.ToString());
        return tVersion;
    }//string GetVersionStringFromAssemblyEmbedded(string pAssemblyDisplayName)


    public static string GetVersionStringFromAssemblyDLL(string pAssemblyDisplayName)
    {
        string tVersion = "Unknown";
        System.Reflection.Assembly tMyAssembly = null;

        tMyAssembly = GetAssemblyDLL(pAssemblyDisplayName);
        if (tMyAssembly == null) { return tVersion; }
        tVersion = GetVersionString(tMyAssembly.GetName().Version.ToString());
        return tVersion;
    }//string GetVersionStringFromAssemblyEmbedded(string pAssemblyDisplayName)

回答by Invincible

var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);

回答by Totero

Here's a nice way using a bit of reflection to get a version of a DLL containing a particular class:

这是使用一点反射来获取包含特定类的 DLL 版本的好方法:

var ver = System.Reflection.Assembly.GetAssembly(typeof(!Class!)).GetName().Version;

Just replace !Class! with the name of a class which is defined in the DLL you wish to get the version of.

只需更换 !Class!使用在您希望获取其版本的 DLL 中定义的类的名称。

This is my preferred method because if I move the DLLs around for different deploys I don't have to change the filepath.

这是我的首选方法,因为如果我为不同的部署移动 DLL,我不必更改文件路径。

回答by Ben Anderson

This works if the dll is .netor Win32. Reflection methods only work if the dll is .net. Also, if you use reflection, you have the overhead of loading the whole dll into memory. The below method does not load the assembly into memory.

如果 dll 是.netWin32 ,这将起作用。反射方法仅在 dll 是 .net 时才有效。此外,如果您使用反射,则需要将整个 dll 加载到内存中。下面的方法不会将程序集加载到内存中。

// Get the file version for the notepad.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll");

// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' +
                  "Version number: " + myFileVersionInfo.FileVersion);

From: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

来自:http: //msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

original source

原始来源

回答by staafl

First of all, there are two possible 'versions' that you might be interested in:

首先,您可能对两种可能的“版本”感兴趣:

  • Windows filesystem file version, applicable to all executable files

  • Assembly build version, which is embedded in a .NET assembly by the compiler (obviously only applicable to .NET assembly dll and exe files)

  • Windows 文件系统文件版本,适用于所有可执行文件

  • 程序集构建版本,由编译器嵌入到 .NET 程序集中(显然仅适用于 .NET 程序集 dll 和 exe 文件)

In the former case, you should use Ben Anderson's answer; in the latter case, use AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version, or Tataro's answer, in case the assembly is referenced by your code.

在前一种情况下,您应该使用 Ben Anderson 的回答;在后一种情况下,请使用AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version或 Tataro 的回答,以防您的代码引用了程序集。

Note that you can ignore all the answers that use .Load()/.LoadFrom()methods, since these actually load the assembly in the current AppDomain - which is analogous to cutting down a tree to see how old it is.

请注意,您可以忽略所有使用.Load()/.LoadFrom()方法的答案,因为这些实际上将程序集加载到当前 AppDomain 中 - 这类似于砍伐一棵树以查看它的年龄。

回答by Wray Smallwood

While the original question may not have been specific to a web service, here is a complete testWebService you can add to display a web service non-cached response plus the file version. We use file version instead of assembly version because we want to know a version, but with all assembly versions 1.0.0.0, the web site can be easily patched (signing and demand link still active!). Replace @Class@ with the name of the web api controller this service is embedded in. It's good for a go/nogo on a web service plus a quick version check.

虽然最初的问题可能不是特定于 Web 服务的,但这里有一个完整的 testWebService,您可以添加它以显示 Web 服务非缓存响应以及文件版本。我们使用文件版本而不是程序集版本,因为我们想知道一个版本,但是对于所有程序集版本 1.0.0.0,网站可以轻松修补(签名和需求链接仍然有效!)。将@Class@ 替换为该服务嵌入的 Web api 控制器的名称。这对于 Web 服务上的 go/nogo 以及快速版本检查很有用。

  [Route("api/testWebService")]
  [AllowAnonymous]
  [HttpGet]
  public HttpResponseMessage TestWebService()
  {
      HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK);
      string loc = Assembly.GetAssembly(typeof(@Class@)).Location;
      FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(loc);
      responseMessage.Content = new StringContent($"<h2>The XXXXX web service GET test succeeded.</h2>{DateTime.Now}<br/><br/>File Version: {versionInfo.FileVersion}");
      responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
      Request.RegisterForDispose(responseMessage);
      return responseMessage;
  }

I found it also necessary to add the following to web.config under configuration to make it truly anonymous

我发现还需要在配置下的 web.config 中添加以下内容以使其真正匿名

<location path="api/testwebservice">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

回答by Prasan Dutt

Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.

@Ben 的回答被证明对我有用。但我需要检查产品版本,因为它是我的软件中发生的主要增量,并遵循语义版本控制。

myFileVersionInfo.ProductVersion

This method met my expectations

这个方法符合我的期望

Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.

更新:我们可以使用程序集获取产品版本,而不是在程序中明确提及 dll 路径(根据生产版本的需要)。

Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location); 
string ProdVersion= fileVersionInfo.ProductVersion;