Reading CSV file and storing values into an array

后端 未结 19 1434
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

相关标签:
19条回答
  • 2020-11-22 07:19

    I have spend few hours searching for a right library, but finally I wrote my own code :) You can read file (or database) with whatever tools you want and then apply the following routine to each line:

    private static string[] SmartSplit(string line, char separator = ',')
    {
        var inQuotes = false;
        var token = "";
        var lines = new List<string>();
        for (var i = 0; i < line.Length; i++) {
            var ch = line[i];
            if (inQuotes) // process string in quotes, 
            {
                if (ch == '"') {
                    if (i<line.Length-1 && line[i + 1] == '"') {
                        i++;
                        token += '"';
                    }
                    else inQuotes = false;
                } else token += ch;
            } else {
                if (ch == '"') inQuotes = true;
                else if (ch == separator) {
                    lines.Add(token);
                    token = "";
                    } else token += ch;
                }
        }
        lines.Add(token);
        return lines.ToArray();
    }
    
    0 讨论(0)
提交回复
热议问题