2011-01-31 95 views
6

我想使用反射來拉項目名稱,執行的程序集的名字,但子方法的過程中它給我「索引超出邊界錯誤的」。獲取使用反射

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

我不明白它爲什麼會在第三行發生錯誤。

Plz Help。

+0

明確項目名稱。代碼不包含項目名稱。 – leppie 2011-01-31 08:07:52

+5

他們已經發明瞭斷點而回... – 2011-01-31 08:08:19

+1

說你的路徑長度爲15個字符,s.Length將15子串2個PARAMS將接受起始索引和長度,不停止索引。所以在你的例子中,你試圖從開始索引中得到15個字符,因此你得到索引超出限制。如果您堅持使用Substring,則需要將第二個參數更改爲s.Length - idx,否則,請按照以下建議使用System.IO.Path.GetFileName。請注意,你的方法將返回\還,所以你真的想要idx + 1,s.Length - idx - 1 – 2011-01-31 08:16:25

回答

14

嘗試:

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

你調試的代碼?你確定第二行返回的值不是-1嗎? 當沒有反斜槓在字符串中發現,LastIndexOf將返回-1,這是不能夠由Substring使用,因此,一個「索引超出範圍」的錯誤將被拋出有效的索引。

一個更安全的方法是將提取使用在路徑類中定義的方法的文件名。 但是,請注意'項目名稱'不必與程序集名稱相同。

1

使用Path類,而不是試圖重新發明輪子和手工計算的子指標。

1

剛剛從調用子串刪除第二個參數。 從文檔:

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

我會嘗試訪問您的集信息文件AssemblyTitle屬性。任何裝配的位置可能與項目名稱不同。試試這個:

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

心連心