Get assembly version in PCL

Deadly 提交于 2019-11-29 17:21:04

问题


I have the following line of code in .NET 4.5 that I am trying to build as Portable Class Library. It's purpose is to get assembly version:

this.GetType().Assembly.GetName().Version.Major;

The problem is that Assembly.GetName() is not available in PCL. Is there a way to get assembly version in PCL?

I know it is possible to parse Assembly.FullName, but I want a better solution.


回答1:


    public static string Version
    {
        get
        {
            var assembly = typeof(MyType).GetTypeInfo().Assembly;
            // In some PCL profiles the above line is: var assembly = typeof(MyType).Assembly;
            var assemblyName = new AssemblyName(assembly.FullName);
            return assemblyName.Version.Major + "." + assemblyName.Version.Minor;
        }
    }



回答2:


I now use the following:

[assembly: AssemblyTitle(AssemblyInfo.AssemblyTitle)]
[assembly: AssemblyProduct(AssemblyInfo.AssemblyProduct)]

[assembly: AssemblyVersion(AssemblyInfo.AssemblyVersion)]
[assembly: AssemblyFileVersion(AssemblyInfo.AssemblyFileVersion)]
[assembly: AssemblyInformationalVersion(AssemblyInfo.AssemblyInformationalVersion)]

internal class AssemblyInfo
{
    public const string AssemblyTitle = "...";
    public const string AssemblyProduct = "...";

    public const string AssemblyVersion = "1.0.0.0";
    public const string AssemblyFileVersion = "1.0.0.0";
    public const string AssemblyInformationalVersion = "1.0.0.0-dev";
}

This allows me to reference any of the constants within the assembly without using reflection, e.g. AssemblyInfo.AssemblyProduct.




回答3:


You are targeting a Silverlight-based platform (Silverlight 4 or higher, Windows Phone before version 8). Those platforms didnt' support the GetName() method. For those platforms, you can define an extension method like this:

public static class AssemblyExtensions
{
    public static AssemblyName GetName(this Assembly assembly)
    {
        return new AssemblyName(assembly.FullName);
    }
}


来源:https://stackoverflow.com/questions/16518131/get-assembly-version-in-pcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!