Get executing assembly name using reflection

爷,独闯天下 提交于 2020-01-10 03:57:05

问题


I am trying to pull the project name using the reflection, but during the substring method it give me "index out of bound error".

string s = System.Reflection.Assembly.GetExecutingAssembly().Location;           
int idx = s.LastIndexOf(@"\");
s = s.Substring(idx, s.Length);

I don't understand why it is giving error on the third line.

Plz Help.


回答1:


Try:

System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)



回答2:


Use the Path class instead of trying to reinvent the wheel and calculating the substring indexes manually.




回答3:


Just remove the second parameter from the call to Substring. From the documentation:

// Exceptions:
//   System.ArgumentOutOfRangeException:
//     startIndex plus length indicates a position not within this instance.  -or-
//     startIndex or length is less than zero.



回答4:


Have you debugged the code ? Are you sure that the 2nd line returns a value other than -1 ? When no backslash is found in the string, LastIndexOf will return -1, which is not a valid index that can be used by Substring and thus, an 'index out of bounds' error will be thrown.

A safer method would be to extract the filename using the methods that are defined in the Path class. But, be aware that the 'project name' is not necessarly the same as the assembly name.




回答5:


I would try accessing the AssemblyTitle Attribute in your AssemblyInfo file. Location of any assembly may not be the same as the project name. Try this:

Assembly a = Assembly.GetEntryAssembly();
AssemblyTitleAttribute titleAttr = (AssemblyTitleAttribute)  a.GetCustomAttributes(typeof(AssemblyTitlenAttribute), false)[0];
Console.WriteLine("Title: " + titleAttr.Title);

hth



来源:https://stackoverflow.com/questions/4848753/get-executing-assembly-name-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!