.net csv 文件的读取 代码

作者:袖梨 2022-06-25

.net csv 文件的读取 代码

public static string[][] read_csv(string text)
{
    if (text == null)
        return null;
    var text_array = new list();
    var line = new list();
    var field = new stringbuilder();
    //是否在双引号内
    bool in_quata = false;
    //字段是否开始
    bool field_start = true;
    for (int i = 0; i < text.length; i++)
    {
        char ch = text[i];
        if (in_quata)
        {
            //如果已经处于双引号范围内
            if (ch == '"')
            {
                //如果是两个引号,则当成一个普通的引号处理
                if (i < text.length - 1 && text[i + 1] == '"')
                {
                    field.append('"');
                    i++;
                }
                else
                    //否则退出引号范围
                    in_quata = false;
            }
            else //双引号范围内的任何字符(除了双引号)都当成普通字符
            {
                field.append(ch);
            }
        }
        else
        {
            switch (ch)
            {
                case ',': //新的字段开始
                    line.add(field.tostring());
                    field.remove(0, field.length);
                    field_start = true;
                    break;
                case '"'://引号的处理
                    if (field_start)
                        in_quata = true;
                    else
                        field.append(ch);
                    break;
                case 'r': //新的记录行开始
                    if (field.length > 0 || field_start)
                    {
                        line.add(field.tostring());
                        field.remove(0, field.length);
                    }
                    text_array.add(line.toarray());
                    line.clear();
                    field_start = true;
                    //在 window 环境下,rn通常是成对出现,所以要跳过
                    if (i < text.length - 1 && text[i + 1] == 'n')
                        i++;
                    break;
                default:
                    field_start = false;
                    field.append(ch);
                    break;
            }
        }
    }
    //文件结束
    if (field.length > 0 || field_start)
        line.add(field.tostring());
    if (line.count > 0)
        text_array.add(line.toarray());
    return text_array.toarray();
}

相关文章

精彩推荐