c#的异常类有一个source属性,默认设置为程序集的名称。 是否有另一种方法来获得这个确切的字符串(而不解析不同的字符串)?

我尝试过以下方法:

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"
}

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

or

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

我使用程序集设置表单的标题如下:

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;
}

你可以使用AssemblyName类来获取程序集的名称,前提是你有程序集的全名:

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

or

AssemblyName.GetAssemblyName(e.Source).Name

MSDN Reference - AssemblyName类


你可以尝试使用System.Reflection.AssemblyTitleAttribute.Title属性的代码:

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


.Location Assembly.GetExecutingAssembly ()


当你不知道程序集的位置,但有它的显示名称(例如ReactiveUI, Version=18.0.0.0, Culture=neutral, PublicKeyToken=null):

var assemblyName = "ReactiveUI, Version=18.0.0.0, Culture=neutral, PublicKeyToken=null"
new AssemblyName(assemblyName).Name // "ReactiveUI"