2017-05-17 45 views
0

我有一個CSV文件,其中包含用逗號分隔的信息,我希望將它們轉換爲類列表(請參閱下面的類)。將CSV讀取到類列表中

抱歉,如果我沒有很好地解釋

例如:

Waiting For Love,Avicii,Tanecni Liga 171,Dance & House,Avicii,,1,2015,,,, 

的問題是,我有一些歌曲使用引號標記和標記引用裏面有個逗號 例如:

Hey Brother,Avicii,TRUE,House,Avicii,,3 of 12,2013,,,"Tim Bergling, Ash Pournouri, Vincent Pontare & Salem Al Fakir", 

問題是我想要那個 - 「Tim Bergling,Ash Pournouri,Vincent P ontare & Salem Al Fakir「將是一個字符串,但如果我用逗號分割,就像我在這裏找到的解決方案一樣,它會在字符串中間切入,我不想要

如果我將使用Split(',');這條線,它會做到這一點:

Hey Brother 
Avicii 
TRUE 
House 
Avicii 
//empty string because there is ',,' 
3 of 12 
2013 
//empty string because there is ',,' 
//empty string because there is ',,' 
"Tim Bergling 
Ash Pournouri 
Vincent Pontare & Salem Al Fakir" 
//empty string because there is ',,' 

相反,我想這一點:

Hey Brother 
Avicii 
TRUE 
House 
Avicii 
//empty string because there is ',,' 
3 of 12 
2013 
//empty string because there is ',,' 
//empty string because there is ',,' 
Tim Bergling, Ash Pournouri, Vincent Pontare & Salem Al Fakir 
//empty string because there is ',,' 

這裏是我的歌曲類:

`public class song 
    { 
     private string name; // Name of the song 
     private string artist; // Name of the artist 
     private string album; // The name of the album 
     private string genre; // The Genre of the song 
     private string album_Artist; // Artist name of the album 
     private string release_Date; // The release date of the song 
     private string track; // The number of the track of the number of the count of the tracks - a.k 4 of 12 
     private string year; // The year that the song came 
     private string comments; // The comments for the song 
     private string description; // The description for the song 
     private string composer; // The composer of the song; 
     private string grouping; // The grouping of the song 
    } 

我有獲取併爲每串套動作(我把它們剪,因爲它太長)

+0

您可能需要使用正則表達式,請參閱http://stackoverflow.com/questions/3776458/split-a-comma-separated-string-with-both-quoted-and-unquoted-strings --ilann – ilann

+0

@ ilann你可能永遠不想使用正則表達式進行解析。使用解析器代替 –

+0

@SirRufo有什麼區別? –

回答

1

不使用任何特殊的圖書館,你可以只是參考Microsoft.VisualBasic程序在你的C#代碼,並使用使用TextFieldParser按以下

(從https://stackoverflow.com/a/3508572/1658434複製)

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv")) 
{ 
    parser.TextFieldType = FieldType.Delimited; 
    parser.SetDelimiters(","); 
    while (!parser.EndOfData) 
    { 
     //Processing row 
     string[] fields = parser.ReadFields(); 
     foreach (string field in fields) 
     { 
      //TODO: Process field 
     } 
    } 
} 

我一直在使用你的榜樣測試,它就像你所需要的。

+0

非常感謝! ,我會在稍後檢查,但這是如何定義內部「」作爲一個字符串? –

+0

好吧,TextFieldParser,顧名思義,是一個解析器。所以我認爲它考慮了分隔文件的規則和格式。 它允許一個字段用雙引號引起來,因此可以識別它。 –