拆分CSV Visual Basic

时间:2011-12-02 22:15:32

标签: vb.net visual-studio visual-studio-2008 csv split

我有一个像

这样的字符串
 Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
 Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455

在一个文件中 在两个单独的行。我正在从文本框中阅读它。我必须在文本框中输出ab563372363_C / R和ab563372356_C / R.我正在尝试使用split函数,但它不起作用..

Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results)  'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)

对于上面的代码,它只是打印整个东西..出了什么问题?

2 个答案:

答案 0 :(得分:2)

试试这个

Private Function GetRequiredText() As List(Of String)
    Dim requiredStringList As New List(Of String)
    Dim file = "test.txt"
    If FileIO.FileSystem.FileExists(file) Then

        Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
        Dim line As String = reader.ReadLine()
        While line IsNot Nothing
            requiredStringList.Add(line.Split(",")(1))
            line = reader.ReadLine()
        End While

        reader.Close()
        reader.Dispose()
    End If
    Return requiredStringList
End Function

这将逐行读取文件,并将您需要的项目添加到函数返回的字符串列表中。

返回List(Of String)可能有点过分,但说明和使用起来非常简单。

然后,您可以遍历列表并使用列表内容执行所需操作。

欢迎评论!!

这也可能有用......

Dim query = From lines In System.IO.File.ReadAllLines(file) _
                    Select lines.Split(",")(1)

这将返回一个IEnumerable(Of String)

享受

答案 1 :(得分:1)

第一

由于您正在阅读整篇文章,因此FileText将以此结尾:

Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455

因此,当您使用这些索引( 1 13 )引用splitString时,您的结果可能会出错。

第二

尝试指定数组的类型,Dim splitString as Array应为Dim splitString As String()

第三

使您的代码更易读/易维护且易于编辑(不仅适合您,还适用于其他人)

代码

Private const FirstIndex = 1
Private const SecondIndex = 12

Sub Main
    Dim myDelimiter As Char

    Dim myString As String
    Dim mySplit As String()

    Dim myResult1 As String
    Dim myResult2 As String

    myDelimiter = ","

    myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
    myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"

    mySplit = myString.Split(myDelimiter)

    myResult1 = mySplit(FirstIndex)
    myResult2 = mySplit(SecondIndex)

    Console.WriteLine(myResult1)
    Console.WriteLine(myResult2)
End Sub