2016-07-09 288 views
-2

该代码从日志文件中读取,如果任何行包含-r和user.Handle,它将用^替换-r, ^,切断:之后的所有内容,然后保存剩余的文本。我收到错误中指定的错误只有有时“System.ArgumentOutOfRangeException:长度不能小于零”

if (line.Contains(user.Handle) && line.Contains("-r")) 
{ 
    string a = line.Replace("-r", "^"); 
    string b = a.Substring(a.IndexOf('^') + 1); 
    string c = b.Substring(0, b.IndexOf(':')); 
    if (!isDuplicate(c)) 
    { 
     listViewEx1.Items.Add(new ListViewItem(user.Handle) 
     { 
      SubItems = { c } 
     }); 
     dupCheck.Add(c); 
     logcount++; 
    } 
+0

什么行是抛出的异常?你能发布你的堆栈跟踪吗? –

+3

您调用的['string.Substring'方法](https://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx)有一个名为'length'的参数。您传入'b.IndexOf(':')'的结果,该结果可能小于零。这是没有什么例外没有*已经*告诉你。 – hvd

回答

2

这是在.NET中使用Substring方法时经常出现的错误。人们经常认为子字符串的起始和结束索引是错误的。它需要起始索引和长度。例如:

public static class MyExtensions 
{ 
    public static string SubstringRange(this string str, int startIndex, int endIndex) 
    { 
     if (startIndex > str.Length - 1) 
      throw new ArgumentOutOfRangeException(nameof(startIndex)); 
     if (endIndex > str.Length - 1) 
      throw new ArgumentOutOfRangeException(nameof(endIndex)); 

     return str.Substring(startIndex, endIndex - startIndex + 1); 
    } 
} 

用法:

string str = "ABC123"; 

int length = str.Length - str.IndexOf("1") + 1; 
string sub = str.Substring(0, length); // ABC1 

或者更好的,这可重复使用的一块添加Java像子字符串在C#中,需要一个开始和结束索引创建一个扩展方法

string str = "ABC123"; 

string sub2 = str.SubstringRange(str.IndexOf("B"), str.IndexOf("2")); // BC12 
相关问题