IndexOutOfRangeException抛出字符串.split c#

时间:2012-05-13 13:18:20

标签: c# .net mysql string

我有一个使用MySQL .Net连接的应用程序,但由于某种原因,我在解析结果时遇到问题会返回它们,

public NameValueCollection[] query(string query)
{
    connect();
    NameValueCollection[] resultSet;

    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader Reader;

    command.CommandText = query;
    connection.Open();
    Reader = command.ExecuteReader();
    string theserows = "";
    while (Reader.Read())
    {
        for (int i = 0; i < Reader.FieldCount; i++){
            theserows += Reader.GetName(i)+"="+Reader.GetValue(i).ToString() + ",";
            Count = i;
        }
        theserows += "\n";
    }
    connection.Close();
    string[] results = theserows.Split(new char[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
    int countResultRows = 0;
    resultSet = new NameValueCollection[Count];
    foreach (string s in results)
    {
        resultSet[countResultRows] = new NameValueCollection();
        string[] result = s.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
        foreach (string col in results)
        {
            if (string.IsNullOrEmpty(col))
                continue;

            string[] kv = col.Split('=');
            resultSet[countResultRows].Add(kv[0], kv[1]);
        }
        countResultRows++;
    }
    return resultSet;
}

在此theserows = "site_id=1,\n"中,string[] result = s.Split(',');上有一个异常{异常IndexOutOfRangeException

任何人都可以了解为什么会出现这种错误吗?

另一方面,我正在阅读它然后构建NameValueCollection的原因是我想添加一个记录完整查询及其结果的日志记录系统

EDIT ::

“count”(小写)更改为countResultRows

CallStack

HTML5Streamer.exe!HTML5Streamer.Classes.MySQL.query(string query) Line 53   C#
HTML5Streamer.exe!HTML5Streamer.Classes.Query.getSiteId(string domain) Line 17 + 0x10 bytes C#
HTML5Streamer.exe!HTML5Streamer.Classes.Query.checkUserPass(string username, string password, string domain) Line 31 + 0xb bytes    C#
HTML5Streamer.exe!HTML5Streamer.Classes.Service.ProccessAdminRequest(System.Net.HttpListenerContext context) Line 239 + 0xd9 bytes  C#
HTML5Streamer.exe!HTML5Streamer.Classes.Service.ProcessRequest(System.Net.HttpListenerContext context) Line 176 + 0xb bytes C#
HTML5Streamer.exe!HTML5Streamer.Classes.Service.ListenerCallback(System.IAsyncResult result) Line 150 + 0xb bytes   C#

Full Exception Detiails

http://i.stack.imgur.com/EST4w.png 第52行是resultSet[countResultRows] = new NameValueCollection();  函数从第26行开始,结束于65

3 个答案:

答案 0 :(得分:1)

在第二个循环之前,您尝试使用逗号作为分隔符来分割字符串“site_id = 1”,结果将是两个字符串的数组,第二个字符串为空。只需将内部foreach循环更改为以下内容:

foreach (string col in result)
{
    if (string.IsNullOrEmpty(col))
        continue;

    string[] kv = col.Split('=');
    resultSet[count].Add(kv[0], kv[1]);
}

答案 1 :(得分:1)

你不应该为2个不同的值(count,Count)使用相同的变量名,即使它在语法上是正确的,这可能会令人困惑。

其次,你应该检查kv长度是否> 1访问数组之前

resultSet[count].Add(kv[0], kv[1]);

如果我遵循你的程序逻辑,给出字符串“site_id = 1,\ n”,分割后, result = {“site_id = 1”,“\ n”},对于第二个字符串kv = {“\ n”},因此kv [1]将返回OutOfRangeException。

以下是我编写代码的方法

string[] results = theserows.Split(new char[]{'\n'},StringSplitOptions.RemoveEmptyEntries);
resultSet = new NameValueCollection[Count];
for(int i = 0; i < results.Length && i < Count; i++)
{
    string s = results[i];
    resultSet[i] = new NameValueCollection();
    string[] result = s.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
    foreach (string col in result) // As pointed by other users, this should be result insead of results, again bad var name choice
    {
        string[] kv = col.Split('=');
        if(kv.Length >= 2)
        resultSet[i].Add(kv[0], kv[1]);
    }
 }

避免任何可能的OutOfRangeExceptions

答案 2 :(得分:1)

你有逗号和空格的尾随问题。另外,当你应该遍历results时,你正在迭代result。试试这个。

string[] results = theserows.Trim().Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); ;
int count = 0;
resultSet = new System.Collections.Specialized.NameValueCollection[results.Length];
foreach (string s in results)
{
    resultSet[count] = new System.Collections.Specialized.NameValueCollection();
    string[] result = s.Trim().Split(new string[] { ","}, StringSplitOptions.RemoveEmptyEntries);
    foreach (string col in result)
    {
        string[] kv = col.Split('=');
        resultSet[count].Add(kv[0], kv[1]);
    }
    count++;
}