Get the name of an executable assembly using reflection

I am trying to pull the project name using reflection, but during the substring method it gives me an "index from related error".

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

I do not understand why it gives an error in the third line.

Help Plz.

+6
reflection c #
source share
5 answers

Try:

 System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location) 
+14
source share

Have you debugged the code? Are you sure the second line returns a value other than -1? If there is no backslash in the string, LastIndexOf will return -1, which is not a valid index that Substring can use, and thus the error "index out of bounds" will be Substring .

A safer method is to extract the file name using the methods defined in the Path class. But keep in mind that the project name does not necessarily match the assembly name.

+1
source share

Use the Path class instead of trying to reinvent the wheel and calculate the substring indices manually.

+1
source share

Just remove the second parameter from the call to the 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. 
+1
source share

I would try to access the AssemblyTitle attribute in the AssemblyInfo file. The location of any assembly may differ from the project name. Try the following:

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

Hth

0
source share

All Articles