2011-10-14 30 views

回答

53
using System.Reflection.Assembly 
using System.Diagnostics.FileVersionInfo 

// ... 

public string GetInformationalVersion(Assembly assembly) { 
    return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion; 
} 
+0

請參閱http://stackoverflow.com/a/19008850/116895 – lance

+7

請注意,如果程序集尚未從文件或UNC加載,則此代碼不起作用。如果程序集嵌入到另一個程序集中(通常是在對程序集進行混淆時)或者出於某種其他原因已使用'Assembly.Load(byte [])加載' – larsmoa

+2

,則可能會出現這種情況。如果您有'mkbundle '你的應用程序Mono – Cocowalla

34
var attr = Assembly 
    .GetEntryAssembly() 
    .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) 
    as AssemblyInformationalVersionAttribute[]; 

它的AssemblyInformationalVersionAttribute陣列。即使沒有搜索類型的屬性,它也不會爲空。

var attr2 = Attribute 
    .GetCustomAttribute(
     Assembly.GetEntryAssembly(), 
     typeof(AssemblyInformationalVersionAttribute)) 
    as AssemblyInformationalVersionAttribute; 

如果該屬性不存在,則可以爲null。

var attr3 = Attribute 
    .GetCustomAttributes(
     Assembly.GetEntryAssembly(), 
     typeof(AssemblyInformationalVersionAttribute)) 
    as AssemblyInformationalVersionAttribute[]; 

同上。

+1

+1;但如果您知道只有一個屬性,則可以使用'GetCustomAttribute'而不是'GetCustomAttributes'。 – vcsjones

+3

@vcsjones只有使用'Attribute'的靜態方法,而不使用'Assembly'的實例方法。 – xanatos

+1

在某些情況下,'Assembly.GetEntryAssembly()'應該被'Assembly.GetExecutingAssembly()'或'Assembly替換。 GetCallingAssembly()'。通常,如果程序集是一個插件,這是必要的 - 在這種情況下,GetEntryAssembly()將返回主機應用程序程序集。 – larsmoa

7
AssemblyInformationalVersionAttribute attribute = 
    (AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly() 
    .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault(); 

if (attribute != null) 
    Console.WriteLine(attribute.InformationalVersion); 
+0

+1,因爲這也適用於Silverlight或Xbox Lakeview! – ahilsend

10

即使問題是有點老了,

我建議採取不同的解決方案,爲我的作品:

Application.ProductVersion 
+4

我很難在WPF中找到它,它是Winforms應用程序類。 :-) – Wouter

3

爲了補充矛的回答:您可以使用Application.ResourceAssembly.Location來找出你的程序集的文件路徑。有了這個有可能獲得AssemblyInformationalVersion字符串中只有一行

System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ResourceAssembly.Location).ProductVersion 
8

在應用程序中使用的已知類型,你可以簡單地這樣做:

using System.Reflection; 

public static readonly string ProductVersion = typeof(MyKnownType).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; 

當然,任何過程中,你用得到的裝配你的屬性應用於良好。請注意,這不依賴於System.Diagnostics或WinForm的Application對象。

0

大廈斷@ Aerthal的答案,如果你想要一個襯墊從MVC Razor視圖得到AssemblyInformationalVersionAttribute:

@System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(Zeroarc.Candid.Web.MvcApplication).Assembly.Location).ProductVersion