在我的c#项目中出现异常Argumentoutofrange

时间:2015-06-15 15:58:10

标签: c# arguments nullreferenceexception

 public void RecievingClients(object obj)
    {
        //TcpListener tp = (TcpListener)obj;
        while (true)
        {
            Socket s;
            s = TcpLogin.AcceptSocket();
            s.ToString();
            NetworkStream ns = new NetworkStream(s);
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);
            string _LPInfo;
             _LPInfo = sr.ReadLine();
            if (_LPInfo.Substring(0, 12) == "&*@Loginn@*&")
             {
                 bool flag;
                 string _LP = _LPInfo.Substring(12);
                 string[] _LPSep;
                 _LPSep =_LP.Split('$');
                 flag = _DBObj.Login(_LPSep[0],_LPSep[1]);
                 if (flag == true)
                 {
                     string ip = LocalIPAddress();
                     sw.WriteLine("&@*IP*@&"+ip+":6090&" + _LPSep[0]);
                     sw.Flush();
                 }
                 else
                 {
                     sw.WriteLine("Login Failed");
                     sw.Flush();
                 }
             }
             else if (_LPInfo.Substring(0, 12) == "&*@SignUp@*&")
             {
                 bool flag;
                 string _LP = _LPInfo.Substring(12);
                 string[] _LPSep;
                 _LPSep = _LP.Split('$');
                 string _SignUpQuery = "INSERT INTO SIGNUP_TABLE (USERNAME,PSWRD) Values('"+_LPSep[0]+ "','" +_LPSep[1] +"');";
                 flag = _DBObj.QueryHandler(_SignUpQuery);
                 if (flag == true)
                 {
                     sw.WriteLine("SignUp Successsfully");
                     sw.Flush();
                 }
                 else
                 {
                     sw.WriteLine("SignUp Failed");
                     sw.Flush();
                 }
             }
这是我的大学项目。这是一个simole聊天信使,当我运行这个所有代码是工作但我有一个例外,如果条件是使用。 if(_LPInfo.Substring(0,12)==“& @Loginn @ &”) 在这里 “mscorlib.dll中发生了'System.ArgumentOutOfRangeException'类型的未处理异常

附加信息:索引和长度必须指代字符串中的位置。“

2 个答案:

答案 0 :(得分:1)

问题出在这里。

    _LPInfo.Substring(0, 12)

12是子串的长度。发生的事情是字符串的长度小于12意味着当使用子字符串时它超出了字符串长度的范围。

使用子字符串时,应确保字符串长度比您检查的字符串数量更大,如下所示。

if (_LPInfo.Length > 9 && _LPInfo.Substring(0, 10) == "&@Loginn@&")
{
    // Do stuff here
}

还要确保计算字符数。 "&安培; @隆吉@&安培;"只有10个字符而不是12个。

答案 1 :(得分:0)

String.Substring从第一个参数开始,并具有第二个参数的长度。如果_LPInfo为null或小于12个字符,则会出现问题...要么使用重载

    if (_LPInfo != null && _LPInfo.Substring(0) == "&*@SignUp@*&")
    {}

或先检查长度

    if (_LPInfo != null && _LPInfo.Length >= 12 && _LPInfo.Substring(0, 12) == "&*@SignUp@*&")
    {}