Windows Store 应用中获取程序集版本号的方法

 本文为个人博客备份文章,原文地址:

http://validvoid.net/windows-store-app-get-assembly-version/

WinRT 中对反射做了很多限制,假设 Windows Store 应用引用了一个程序集 MyApp.Utils,其中有一个类叫做 MyUtils,可以使用以下方法获得程序集 MyApp.Utils的版本号和文件版本号。

获得程序集版本号

方法一

using System.Reflection;

public static string GetAssemblyVersion()
{
    return Assembly.Load(new AssemblyName("MyApp.Utils"))
        .GetName().Version.ToString();
}

 

注意方法一有两个限制条件,一是要求知道程序集的完整显示名称;二是程序集输出类型必须是“类库”(Class Library)。当程序集输出类型是“Windows 运行时组件”(Windows Runtime Component)时,方法一将返回如下错误:

Could not load file or assembly 'MyApp.Utils, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.  

方法二

using System.Reflection;

public static string GetAssemblyVersion()
{
    return typeof(MyUtils).GetTypeInfo().Assembly.GetName().Version.ToString();
}

 

方法二在程序集输出类型为类库或者 Windows 运行时组件时均可用,其限制条件是需知道程序集中的一个类,再通过 typeof(MyUtils).GetTypeInfo().Assembly 取得目标程序集,进而获得程序集的版本号。

获得程序集文件版本号

using System.Reflection;

public static string GetAssemblyFileVersion()
{
    return
        CustomAttributeExtensions.GetCustomAttribute(
            typeof(MyUtils).GetTypeInfo().Assembly).Version;
}

 

CustomAttributeExtensions 类包含了可以获得自定义特性的静态方法,可以通过此类,获得 AssemblyFileVersionAttribute 特性的值,也就是程序集的文件版本号。

可用性

以上方法在 Windows/ Windows Phone 8.1 Universal 以及 Windows 10 UWP 中测试可用。

参考

posted @ 2015-11-18 00:26  void²  阅读(643)  评论(0编辑  收藏  举报