【问题标题】:Get executing assembly name using reflection使用反射获取正在执行的程序集名称
【发布时间】:2011-01-31 08:04:45
【问题描述】:

我正在尝试使用反射提取项目名称,但在子字符串方法期间它给了我“索引超出范围错误”。

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

我不明白为什么它在第三行给出错误。

请帮助。

【问题讨论】:

  • 明确项目名称。代码不包含项目名称。
  • 他们早就发明了断点...
  • 假设您的路径长度为 15 个字符,s.Length 将为 15。具有 2 个参数的子字符串将接受开始索引和长度,而不是停止索引。因此,在您的示例中,您试图从起始索引中获取 15 个字符,因此索引超出范围。如果您坚持使用 Substring,则需要将第二个参数更改为 s.Length - idx,否则,请按照下面的建议使用 System.IO.Path.GetFileName。请注意,您的方法也会返回 \,所以您真的想要 idx + 1, s.Length - idx - 1

标签: c# .net reflection


【解决方案1】:

试试:

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

【讨论】:

  • 项目名称不一定与程序集名称相同。
【解决方案2】:

使用Path 类而不是尝试重新发明轮子并手动计算子字符串索引。

【讨论】:

    【解决方案3】:

    只需从对 Substring 的调用中删除第二个参数。 来自文档:

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

    【讨论】:

      【解决方案4】:

      你调试过代码吗?您确定第二行返回的值不是 -1 吗? 如果在字符串中没有找到反斜杠,LastIndexOf 将返回 -1,这不是 Substring 可以使用的有效索引,因此将引发“索引超出范围”错误。

      更安全的方法是使用 Path 类中定义的方法提取文件名。 但是,请注意,“项目名称”不一定与程序集名称相同。

      【讨论】:

        【解决方案5】:

        我会尝试访问您的 AssemblyInfo 文件中的 AssemblyTitle 属性。任何程序集的位置可能与项目名称不同。试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-19
          • 2018-07-09
          • 1970-01-01
          • 2012-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多