2010-11-24 155 views
128

C#的異常類具有默認情況下設置爲程序集名稱的源屬性。
是否有另一種方法來得到這個確切的字符串(不解析不同的字符串)?獲取程序集名稱

我曾嘗試以下:

catch(Exception e) 
{ 
    string str = e.Source;   
    //"EPA" - what I want    
    str = System.Reflection.Assembly.GetExecutingAssembly().FullName; 
    //"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
    str = typeof(Program).FullName; 
    //"EPA.Program" 
    str = typeof(Program).Assembly.FullName; 
    //"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
    str = typeof(Program).Assembly.ToString(); 
    //"EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
    str = typeof(Program).AssemblyQualifiedName; 
    //"EPA.Program, EPA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 
} 

回答

236
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name 

typeof(Program).Assembly.GetName().Name; 
+0

VS在解析使用時顯示錯誤。您可以使用Assembly.GetEntryAssembly()。GetName()。Name; – Butsaty 2016-05-30 07:48:08

+2

其實它應該是typeof(any).GetTypeInfo()。Assembly – Thaina 2016-12-16 15:43:26

6

我用大會設置窗體的標題,例如:

private String BuildFormTitle() 
{ 
    String AppName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; 
    String FormTitle = String.Format("{0} {1} ({2})", 
            AppName, 
            Application.ProductName, 
            Application.ProductVersion); 
    return FormTitle; 
} 
1

您可以使用AssemblyName類來獲取組合LY的名字,只要你有對裝配的全名:

AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name 

AssemblyName.GetAssemblyName(e.Source).Name 

MSDN Reference - AssemblyName Class

2

你可以試試這個代碼,它使用System.Reflection.AssemblyTitleAttribute.Title屬性:

((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title;

相關問題