2010-11-24 156 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;

相关问题