使用反射获取执行程序集名称

6
我正在尝试使用反射来获取项目名称,但在使用子字符串方法时出现“索引超出范围”的错误。
string s = System.Reflection.Assembly.GetExecutingAssembly().Location;           
int idx = s.LastIndexOf(@"\");
s = s.Substring(idx, s.Length);

我不明白为什么第三行会出错。

请帮忙。


澄清项目名称。代码中不包含项目名称。 - leppie
5
他们一段时间以前发明了断点... - Yochai Timmer
1
假设您的路径长度为15个字符,则s.Length将为15。带有2个参数的子字符串函数接受起始索引和长度,而不是结束索引。因此,在您的示例中,您尝试从起始索引获取15个字符,因此出现了越界错误。如果您坚持使用Substring,您需要将第二个参数更改为s.Length-idx,否则,请按下面建议的方式使用System.IO.Path.GetFileName。请注意,您的方法还会返回\,因此您实际上需要的是idx + 1,s.Length-idx-1。 - Jimmy Chandra
5个回答

14

尝试:

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

5
项目名称不一定与程序集名称相同。 - Frederik Gheysels

1

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

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

1

你调试过代码了吗?你确定第二行返回的值不是-1吗? 当字符串中没有反斜杠时,LastIndexOf会返回-1,这不是可以被Substring使用的有效索引,因此会抛出“索引超出范围”的错误。

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


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

0
我建议您尝试访问 AssemblyInfo 文件中的 AssemblyTitle 属性。任何程序集的位置可能与项目名称不同。请尝试以下操作:
Assembly a = Assembly.GetEntryAssembly();
AssemblyTitleAttribute titleAttr = (AssemblyTitleAttribute)  a.GetCustomAttributes(typeof(AssemblyTitlenAttribute), false)[0];
Console.WriteLine("Title: " + titleAttr.Title);

hth


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接