简体   繁体   English

从vb.net中的文件中提取值

[英]Value extraction from file in vb.net

The following is a piece of code which I use in my project: 以下是我在项目中使用的一段代码:

Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(OpenFileDialog1.FileName.ToString())
    Reader.TextFieldType = FileIO.FieldType.Delimited
    Reader.SetDelimiters("\t")
    Dim currentRow As String()
    Dim valueArray() As Double = {0, 0, 0, 0}
    Dim power3, power2, power1, constVar As Double
    power3 = 0.0
    power2 = 0.0
    power1 = 0.0
    constVar = 0.0
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentString As String
            Dim i As Integer = 0
            Dim j As Integer = 0
            For Each currentField As String In currentRow
                currentString = currentField(0)
                MsgBox(currentField)
                MsgBox(currentString)
            Next
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
        End Try
    End While
End Using

The text file from which I am reading contains floating point values separated with tabs, like this: 我正在阅读的文本文件包含用制表符分隔的浮点值,如下所示:

0.5 0.6 0.7 0.8 0.5 0.6 0.7 0.8

However, right now, when I run the code, I get the complete line as a string "0.5 0.6 0.7 0.8" 但是,现在,当我运行代码时,我将完整的行作为字符串"0.5 0.6 0.7 0.8"

I am having trouble extracting each float value. 我无法提取每个浮点值。 Please suggest some methods of extracting each value so that i can store them separately. 请建议一些提取每个值的方法,以便我可以单独存储它们。

The TextFieldParser class is supposed to split apart all the fields on each line for you. TextFieldParser类应该为您拆分每行的所有字段。 If it does not do so, it's because you haven't set it up properly. 如果没有这样做,那是因为你还没有正确设置它。 In this case, it looks like your problem is the following line: 在这种情况下,看起来您的问题是以下行:

Reader.SetDelimiters("\t")

While that kind of string-literal syntax would work in C# and other similar languages, that won't work in VB.NET. 虽然这种字符串文字语法可以在C#和其他类似语言中使用,但这在VB.NET中不起作用。 The backslash character is not an escape character in VB.NET, so the string is taken exactly as you typed it. 反斜杠字符不是VB.NET中的转义字符,因此字符串与您键入的字符串完全相同。 So the TextFieldParser is looking for a two-character string consisting of a backslash followed by the letter t rather than a single tab character. 因此, TextFieldParser正在寻找一个由两个字符组成的字符串,该字符串由反斜杠后跟字母t而不是单个制表符组成。 If you want to use the tab character as a delimiter, as I strongly suspect is what you intended, then, in VB.NET, you need to do this: 如果你想使用制表符作为分隔符,因为我强烈怀疑你的意图,那么,在VB.NET中,你需要这样做:

Reader.SetDelimiters(ControlChars.Tab)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM