" System.ArgumentOutOfRangeException:长度不能小于零"

时间:2016-07-09 17:16:01

标签: c#

此代码从日志文件中读取,如果任何行包含-r和user.Handle,它将替换-r并删除^之前的所有内容,切断:之后的所有内容,然后保存剩下的文字。我收到标题中指定的错误仅限某些内容

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++;
    }

1 个答案:

答案 0 :(得分:3)

使用Substring方法时,这是.NET中的一个常见错误。人们通常认为Substring采用错误的起始和结束索引。它采用起始索引和长度。例如:

string str = "ABC123";

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

或者更好的是,为这个可重用的部分创建一个扩展方法,在C#中添加带有起始和结束索引的Java Like 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";

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