2015-10-26 91 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