[英]Value extraction from file in vb.net
以下是我在項目中使用的一段代碼:
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
我正在閱讀的文本文件包含用制表符分隔的浮點值,如下所示:
0.5 0.6 0.7 0.8
但是,現在,當我運行代碼時,我將完整的行作為字符串"0.5 0.6 0.7 0.8"
我無法提取每個浮點值。 請建議一些提取每個值的方法,以便我可以單獨存儲它們。
TextFieldParser
類應該為您拆分每行的所有字段。 如果沒有這樣做,那是因為你還沒有正確設置它。 在這種情況下,看起來您的問題是以下行:
Reader.SetDelimiters("\t")
雖然這種字符串文字語法可以在C#和其他類似語言中使用,但這在VB.NET中不起作用。 反斜杠字符不是VB.NET中的轉義字符,因此字符串與您鍵入的字符串完全相同。 因此, TextFieldParser
正在尋找一個由兩個字符組成的字符串,該字符串由反斜杠后跟字母t而不是單個制表符組成。 如果你想使用制表符作為分隔符,因為我強烈懷疑你的意圖,那么,在VB.NET中,你需要這樣做:
Reader.SetDelimiters(ControlChars.Tab)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.