2015-10-26 90 views
3

我正在使用CsvHelper将数据读取/写入到Csv文件中。现在我想解析csv文件的分隔符。我怎样才能得到这个?CsvHelper:如何从给定的csv文件中检测分隔符

我的代码:

 var parser = new CsvParser(txtReader); 
    delimiter = parser.Configuration.Delimiter; 

我总是有分隔符 “” 但实际上在CSV文件分隔符是 “\ t” 的。

回答

2

CSV是Comma分隔值。我认为你不能可靠地检测出是否有不同的角色使用了分隔符。如果有一个标题行,那么你可以指望它。

您应该知道使用的分隔符。您应该能够在打开文件时看到它。如果文件的来源每次都给你一个不同的分隔符,并且不可靠,那么我很抱歉。 ;)

如果你只是想使用不同的分隔符进行解析,那么你可以设置csv.Configuration.Delimiterhttp://joshclose.github.io/CsvHelper/#configuration-delimiter

+0

感谢您的评论。 – jamie2015

+0

@JoshClose虽然CSV代表逗号分隔值,但不同的区域设置将具有不同的分隔符。例如,在荷兰,我们用分号作为列表分隔符。我在想;为什么CsvHelper不采用CultureInfo的默认分隔符?这样,如果您执行一些忽略语言环境的自定义CSV,则只需要覆盖默认的分隔符。 –

+0

如果你想记录一个问题,我认为这将是一个简单的改变。 https://github.com/JoshClose/CsvHelper/issues –

3

我发现这段代码在这个site

public static char Detect(TextReader reader, int rowCount, IList<char> separators) 
{ 
    IList<int> separatorsCount = new int[separators.Count]; 

    int character; 

    int row = 0; 

    bool quoted = false; 
    bool firstChar = true; 

    while (row < rowCount) 
    { 
     character = reader.Read(); 

     switch (character) 
     { 
      case '"': 
       if (quoted) 
       { 
        if (reader.Peek() != '"') // Value is quoted and 
      // current character is " and next character is not ". 
         quoted = false; 
        else 
         reader.Read(); // Value is quoted and current and 
       // next characters are "" - read (skip) peeked qoute. 
       } 
       else 
       { 
        if (firstChar) // Set value as quoted only if this quote is the 
       // first char in the value. 
         quoted = true; 
       } 
       break; 
      case '\n': 
       if (!quoted) 
       { 
        ++row; 
        firstChar = true; 
        continue; 
       } 
       break; 
      case -1: 
       row = rowCount; 
       break; 
      default: 
       if (!quoted) 
       { 
        int index = separators.IndexOf((char)character); 
        if (index != -1) 
        { 
         ++separatorsCount[index]; 
         firstChar = true; 
         continue; 
        } 
       } 
       break; 
     } 

     if (firstChar) 
      firstChar = false; 
    } 

    int maxCount = separatorsCount.Max(); 

    return maxCount == 0 ? '\0' : separators[separatorsCount.IndexOf(maxCount)]; 
} 

随着separators是,你可以有可能的分隔符。

希望能够帮助:)

+1

感谢您发表本文并援引参考文献。是的,CSV是用逗号分隔的,但我们都知道用户不会总是遵守规则并且正确地验证有时我们需要写些疯狂的东西 – agrath