什麼是在運行時獲取程序集的AssemblyInformationalVersion
屬性值的C#語法?例如:獲取.NET程序集的AssemblyInformationalVersion值?
[assembly: AssemblyInformationalVersion("1.2.3.4")]
什麼是在運行時獲取程序集的AssemblyInformationalVersion
屬性值的C#語法?例如:獲取.NET程序集的AssemblyInformationalVersion值?
[assembly: AssemblyInformationalVersion("1.2.3.4")]
using System.Reflection.Assembly
using System.Diagnostics.FileVersionInfo
// ...
public string GetInformationalVersion(Assembly assembly) {
return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
}
http://msdn.microsoft.com/en-us/library/system.reflection.assemblyinformationalversionattribute.aspx
看看在InformationalVersion財產
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;但如果您知道只有一個屬性,則可以使用'GetCustomAttribute'而不是'GetCustomAttributes'。 – vcsjones
@vcsjones只有使用'Attribute'的靜態方法,而不使用'Assembly'的實例方法。 – xanatos
在某些情況下,'Assembly.GetEntryAssembly()'應該被'Assembly.GetExecutingAssembly()'或'Assembly替換。 GetCallingAssembly()'。通常,如果程序集是一個插件,這是必要的 - 在這種情況下,GetEntryAssembly()將返回主機應用程序程序集。 – larsmoa
AssemblyInformationalVersionAttribute attribute =
(AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault();
if (attribute != null)
Console.WriteLine(attribute.InformationalVersion);
+1,因爲這也適用於Silverlight或Xbox Lakeview! – ahilsend
即使問題是有點老了,
我建議採取不同的解決方案,爲我的作品:
Application.ProductVersion
我很難在WPF中找到它,它是Winforms應用程序類。 :-) – Wouter
爲了補充矛的回答:您可以使用Application.ResourceAssembly.Location
來找出你的程序集的文件路徑。有了這個有可能獲得AssemblyInformationalVersion字符串中只有一行
System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ResourceAssembly.Location).ProductVersion
在應用程序中使用的已知類型,你可以簡單地這樣做:
using System.Reflection;
public static readonly string ProductVersion = typeof(MyKnownType).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
當然,任何過程中,你用得到的裝配你的屬性應用於良好。請注意,這不依賴於System.Diagnostics
或WinForm的Application
對象。
大廈斷@ Aerthal的答案,如果你想要一個襯墊從MVC Razor視圖得到AssemblyInformationalVersionAttribute:
@System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(Zeroarc.Candid.Web.MvcApplication).Assembly.Location).ProductVersion
請參閱http://stackoverflow.com/a/19008850/116895 – lance
請注意,如果程序集尚未從文件或UNC加載,則此代碼不起作用。如果程序集嵌入到另一個程序集中(通常是在對程序集進行混淆時)或者出於某種其他原因已使用'Assembly.Load(byte [])加載' – larsmoa
,則可能會出現這種情況。如果您有'mkbundle '你的應用程序Mono – Cocowalla