Get executing assembly name using reflection

前端 未结 5 1054
清酒与你
清酒与你 2020-12-19 09:00

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.Reflec         


        
相关标签:
5条回答
  • 2020-12-19 09:28

    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.

    0 讨论(0)
  • 2020-12-19 09:29

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

    0 讨论(0)
  • 2020-12-19 09:32

    Try:

    System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)
    
    0 讨论(0)
  • 2020-12-19 09:35

    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

    0 讨论(0)
  • 2020-12-19 09:45

    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.
    
    0 讨论(0)
提交回复
热议问题