6

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.

3
  • Clarify project name. Code does not contain project names. Commented Jan 31, 2011 at 8:07
  • 5
    They've invented breakpoints a while back... Commented Jan 31, 2011 at 8:08
  • 1
    Say your path length is 15 chars, s.Length will be 15. Substring with 2 params will accept the beginning index and the length, NOT the stop index. So in your example, you are trying to get 15 characters from the start index, thus you get index out of bound. If you insist on using Substring, you need to change the second param to s.Length - idx instead, otherwise, use System.IO.Path.GetFileName as suggested below. Mind you, your method will return the \ also, so you really want idx + 1, s.Length - idx - 1 Commented Jan 31, 2011 at 8:16

5 Answers 5

14

Try:

System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Sign up to request clarification or add additional context in comments.

1 Comment

the project name is not necessarly the same as the assembly name.
1

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

Comments

1

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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.