2013-02-08 202 views
-1

我有一個CSV文件中的兩列,我需要將每列存儲在一個單獨的數組中。如何從CSV文件讀取數據並將信息存儲到數組中?

Name,AvalibilityAsBoolean 
--------------------------- 
Vagarth Gaurav,True 
Dhananjay Menon,False 

我想有一個數組作爲名稱,另一個數組作爲布爾值存儲類似於下面。

Name(0) = "Vagarth Gaurav" 
Name(1) = "Dhananjay Menon" 
Available(0) = True 
Available(1) = False 

唯一的問題是讀取CSV並將字符串和布爾值存儲到適當的數組中。

請幫忙,我是VB新手。我正在使用Visual Basic 2010

+0

可能重複(http://stackoverflow.com/questions/736629/parse-delimited-csv-in-net) – CloudyMarble

回答

2

我確定這個問題已被問過,但這應該有所幫助。利用TextFieldParser Class爲您解析可以讓您輕鬆完成。代碼示例中也顯示了用於管理這兩個數組的代碼。

Dim arrName() As String 
    Dim arrValue() As String 

    Using ioReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\test\test.csv") 

     ioReader.TextFieldType = FileIO.FieldType.Delimited 
     ioReader.SetDelimiters(",") 

     While Not ioReader.EndOfData 

      Dim arrCurrentRow As String() = ioReader.ReadFields() 

      If arrName Is Nothing Then 

       ReDim Preserve arrName(0) 
       ReDim Preserve arrValue(0) 

       arrName(0) = arrCurrentRow(0) 
       arrValue(0) = arrCurrentRow(1) 

      Else 

       ReDim Preserve arrName(arrName.Length) 
       ReDim Preserve arrValue(arrValue.Length) 

       arrName((arrName.Length - 1)) = arrCurrentRow(0) 
       arrValue((arrValue.Length - 1)) = arrCurrentRow(1) 

      End If 

     End While 
+0

謝謝版本很多@NoAlias。它完美的作品! – Gaurav

1
Dim sData() As String 
Dim arrName, arrValue as New List(Of String)() 

Using sr As New StreamReader(sFile) 
    While Not sr.EndOfStream 
     sData = sr.ReadLine().Split(","c) 

     arrName.Add(sData(0).Trim()) 
     arrValue.Add(sData(1).Trim()) 
    End While 
End Using 

你也許要存儲值作爲Boolean(可用,不可用的)。你可以這樣做:

Dim arrValue As New List(Of Boolean)() 
... 

    arrValue.Add(Not sData(1).Trim().ToUpper().StartsWith("NOT")) 
[解析分隔CSV在.NET]的
+0

非常感謝你! – Gaurav

相關問題