读取CSV文件并将值存储到字典中

时间:2016-06-03 17:24:55

标签: c# arrays algorithm csv dictionary

我正在尝试阅读test.csv文件。像这样;

"test.try1.get1","START"

"test.try1.get2","Get 111"
"test.try1.get3","Get 222, 333"
"test.try1.get4","Get {test}, [{test2}, {test3]"
"test.try1.get5","Get \"{test}\", [{test2}, {test3]"


"test.try2.get1","Bla bla bla... bla bla bla...
Bla bla bla bla bla bla bla...
Bla bla bla bla bla bla bla... (:

BLA?"

"test.try2.get2","Bla bla bla... bla bla bla...

 • 1 - Bla bla bla bla bla bla bla...
 • 2 - Bla bla bla bla bla bla bla...

Bla bla bla \" bla bla bla bla... (: \"

BLA?"

"test.try3.get1","BONUSSS!!!"
"test.try3.get2","BONUSSS!!! \" "

"test.try4.get1","END"

我可以使用test.csv阅读StreamReader文件,并能够使用Split()功能分隔每一行。我想将每列存储到单独的字典中,然后显示它。喜欢;

Console.WriteLine(GetText(test.try1.get1)); //OUTPUT: START (WITHOUT ("))

我认为,这段代码很糟糕。

- 我如何改善表现? - 如何缩短此代码? - 是"代码逻辑"好吗? -有人能帮我吗 ? (:

我的工作代码

public static Dictionary<string, string> texts = new Dictionary<string, string>();
    public static void LoadCSV() {
        using (StreamReader reader = new StreamReader(@"test.csv")) {

            string total = string.Empty;
            bool multipleLine = false;

            while (!reader.EndOfStream) {
                string line = reader.ReadLine().ToString();

                if (!multipleLine && line.StartsWith("\"") && !line.EndsWith("\"") && line != string.Empty) {
                    multipleLine = true;
                }

                if(multipleLine && line == string.Empty) {
                    total += "\n\n";
                    continue;
                }

                if (!multipleLine && line == string.Empty) {
                    continue;
                }

                if (multipleLine && !line.StartsWith("\"") && !line.EndsWith("\"") && line != string.Empty) {
                    total += line;
                    continue;
                }
                else if (multipleLine && !line.StartsWith("\"") && line.EndsWith("\"") && line != string.Empty) {
                    total += line;
                    multipleLine = false;
                }

                if (!multipleLine && line.StartsWith("\"") && line.EndsWith("\"") && line != string.Empty) {
                    total = line;
                }

                string[] splitted = total.Split(',');

                if (!texts.ContainsKey(splitted[0])) {
                    //Index out of range
                    texts.Add(splitted[0].Replace("\"", string.Empty), splitted[1]);
                    Console.WriteLine(string.Format("ADDED : {0} , {1}", splitted[0], splitted[1]));
                }

                total = string.Empty;
                multipleLine = false;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果你能保证文件的大小合理,我只需将整个文件读入内存并在其上运行一个正则表达式。然后遍历匹配并将它们添加到字典中。

这个SO答案中给出的正则表达式应该对你有用:

C#, regular expressions : how to parse comma-separated values, where some values might be quoted strings themselves containing commas