【问题标题】:C# CSV file to array/listC# CSV 文件到数组/列表
【发布时间】:2013-04-18 05:04:03
【问题描述】:

我想在 C# 的某个数组中读取 4-5 个 CSV 文件

我知道有人问过这个问题,并且我已经解决了这些问题... 但是我对 CSV 的使用太简单了……

我有包含以下数据类型列的 csv 文件....

string , string

这些字符串没有','所以没有张力...... 而已。而且它们并不大。每个只有大约 20 条记录。

只是想将它们读入到 C# 数组中......

有没有什么非常非常简单直接的方法可以做到这一点?

【问题讨论】:

  • 看那边的相关问题 -->
  • 什么是“C#数组”?
  • @GrantThomas:一大把眼镜? (可能是一部新的克林特伊斯特伍德电影,讲述亡命之徒面临老年和视力不佳的蹂躏)

标签: c# .net csv csv-import


【解决方案1】:

要读取文件,请使用

TextReader reader = File.OpenText(filename);

读取一行:

string line = reader.ReadLine()

然后

string[] tokens = line.Split(',');

将它们分开。

通过在最后两个示例行周围使用循环,您可以将每个标记数组添加到列表中,如果这是您需要的话。

【讨论】:

  • 如果列条目在字符串值中包含逗号怎么办?
  • 好吧,如果 CSV 文件是逗号分隔的,那么令牌中的逗号要么是非法的,要么是无法正确解析的。定界字符显然应该是标记中未使用的字符。如果主题开始在他的单元格中使用逗号,我会假设他不会导出到逗号分隔列表!
  • 这完全是错误的,作为一名程序员,我希望人们知道 一些 转义值。
  • 给定一个仅包含以下内容的 CSV 文件:a,b,c,d,e,f,g 您知道这些来自 2 个单元格。你怎么知道哪些字母来自哪些单元格?
  • a,'a,b,c,d,e,f,g' ... 或者可能会有自定义的闹剧,a,a\,b\,c\,d\,e\,f\,g。诚然很奇怪,但为了这个目的,让我们假设它超出了处理输入应如何显示的范围,只需要正确解析,使用斜线和所有...但是 still 仅将该字符串作为单个价值。
【解决方案2】:

这包括字段中的引号和逗号。 (假设你一次做一行)

using Microsoft.VisualBasic.FileIO;   //For TextFieldParser

// blah blah blah

StringReader csv_reader = new StringReader(csv_line);

TextFieldParser csv_parser = new TextFieldParser(csv_reader);
csv_parser.SetDelimiters(",");
csv_parser.HasFieldsEnclosedInQuotes = true;
string[] csv_array = csv_parser.ReadFields();

【讨论】:

    【解决方案3】:

    这是一种将 CSV 内容获取到字符串数组的简单方法。 CSV 文件可以有双引号、回车换行和分隔符是逗号。 以下是您需要的库:

    System.IO; System.Collection.Generic;

    System.IO 用于 FileStreamStreamReader 类访问您的文件。这两个类都实现了IDisposable 接口,因此您可以使用using 语句来关闭您的流。 (下例)

    System.Collection.Generic 命名空间用于集合,例如IListListArrayList 等...在这个例子中,我们将使用List 类,因为列表比数组更好老实说。但是,在返回出站变量之前,我会调用.ToArray() 成员方法来返回数组。

    有很多方法可以从文件中获取内容,我个人更喜欢使用while(condition) 循环来遍历内容。在condition 子句中,使用!lReader.EndOfStream。当不是流结束时,继续迭代文件。

    public string[] GetCsvContent(string iFileName)
    {
        List<string> oCsvContent = new List<string>();
        using (FileStream lFileStream = 
                      new FileStream(iFilename, FileMode.Open, FileAccess.Read))
        {
            StringBuilder lFileContent = new StringBuilder();
            using (StreamReader lReader = new StreamReader(lFileStream))
            {
                // flag if a double quote is found
                bool lContainsDoubleQuotes = false; 
                // a string for the csv value
                string lCsvValue = "";
                // loop through the file until you read the end
                while (!lReader.EndOfStream)
                {
                    // stores each line in a variable
                    string lCsvLine = lReader.ReadLine();
                    // for each character in the line...
                    foreach (char lLetter in lCsvLine)
                    {
                        // check if the character is a double quote
                        if (lLetter == '"')
                        {
                            if (!lContainsDoubleQuotes)
                            {
                                lContainsDoubleQuotes = true;
                            }
                            else
                            {
                                lContainsDoubleQuotes = false;
                            }
                        }
                        // if we come across a comma 
                        // AND it's not within a double quote..
                        if (lLetter == ',' && !lContainsDoubleQuotes)
                        {
                            // add our string to the array
                            oCsvContent.Add(lCsvValue);
                            // null out our string
                            lCsvValue = "";
                        }
                        else
                        {
                            // add the character to our string
                            lCsvValue += lLetter;
                        }
                    }
                }
            }
        }
        return oCsvContent.ToArray();
    }
    

    希望这会有所帮助!非常容易而且非常快速。 干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2019-01-03
      • 2013-02-15
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多