2011-11-04 55 views
0

爲什麼我越來越:C#編譯器錯誤與子串

Index and length must refer to a location within the string. 
Parameter name: length 

當我編譯此代碼: http://pastebin.com/CW4EcCM8

它的某些部分:

public string findFileEnding(string file) 
    { 
     int index1 = file.IndexOf('.'); 
     file = file.Substring(index1, file.Length); 
     return file; 
    } 

感謝;)

+0

有沒有支票,索引1是> -1(這還出現了。在字符串中)。如果你做一個子字符串W /索引:-1它也會引發錯誤... – Rikon

+1

不是你的問題的答案,但更可靠的方式來找到文件擴展名是使用路徑類:http:// msdn。 microsoft.com/en-us/library/system.io.path.aspx –

+0

@Rikon相同的錯誤,但有不同的信息... –

回答

2

Substring的第二個參數(如果存在)是所需的長度o f子串。因此,您要求的字符串的長度與file的長度相同,但是從可能不同於0的位置開始。這會使您的子字符串的末尾超過file的末尾。

假設你想獲得的所有的file開始index1位置,你可以離開了第二個參數乾脆:

file = file.Substring(index1); 

爲了使這個強大的,你會希望把一些更多的檢查:

  1. file可能是null
  2. IndexOf的返回值可能是-1。如果file不包含點,則會發生這種情況。
+0

可能想提及OP應該檢查返回-1的'IndexOf'。 – CodeNaked

0

這不是一個編譯器錯誤,這是一個運行時錯誤。

注意事項String.Substring(int, int)的文檔:

檢索從這個實例子。子字符串從指定的字符位置[startIndex]開始,並具有指定的長度[length]。

所以將有指定的長度。因此,從startIndex開始必須有足夠的字符才能返回指定長度的子字符串。因此,下面的不等式必須滿足String.Substringsstring的實例成功:

startIndex >= 0 
length >= 0 
length > 0 implies startIndex + length <= s.Length 

請注意,如果你只是想從index到字符串末尾的子串,你可以說

s.Substring(index); 

在這裏,唯一的限制是

startIndex>= 0 
startIndex < s.Length 
0

你會想要做類似日是:

public string FindFileEnding(string file) 
{ 
    if (string.IsNullOrEmpty(file)) 
    { 
     // Either throw exception or handle the file here 
     throw new ArgumentNullException(); 
    } 
    try 
    { 
     return file.Substring(file.LastIndexOf('.')); 
    } 
    catch (Exception ex) 
    { 
     // Handle the exception here if you want, or throw it to the calling method 
     throw ex; 
    } 
} 
+0

我假設你的意思是'string.IsNullOrEmpty(file)'爲你的第一個if語句,因爲除非你定義了自定義的擴展方法,否則你所擁有的是無效的。你還應該檢查'LastIndexOf'的返回值。重新思考這個例外是沒有道理的。 – CodeNaked

+0

@CodeNaked感謝代碼檢查,很難在瀏覽器中完成。那裏有任何驗證C#的網站嗎?它並不意味着完整的答案,只是一個起點。如果最後一個索引無效,那麼您必須在處理之前或之後處理它。我原本用'int index = file.LastIndexOf('。')'把它刪除了,因爲沒有任何說明他們想如何處理錯誤或錯誤的值 – John

+1

我不知道有任何網站可以這樣做,但那裏是一些[輕量級工具](http://stackoverflow.com/questions/2775055/looking-for-replacement-for-snippet-compiler)。 – CodeNaked