这是我读取txtfile并将其放入datagridview
的代码Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
ofd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
ofd1.FilterIndex = 2
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
End If
'if the filename is existing
If System.IO.File.Exists(filename) = True Then
Dim objReader As New System.IO.StreamReader(filename)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End If
这是txt文件:
False, 1-305-9097-01-2, 879.75, 122009, fr
False, 1-305-9097-02-2, 879.75, 122009, fr
False, 1-305-9097-02-3, 879.75, 122009, fr
False, 1-305-9097-03-5, 899.75, 122009, fr
现在我想只得到我的txtfile的第一条记录并把它放在msgbox中,我该怎么做?
我试过了:
MsgBox(SplitLine.tostring)
但是这段代码的输出是这样的: System.String []
谢谢。
答案 0 :(得分:1)
Dim First as Boolean = True
像这样编辑循环:
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
If First Then MessageBox(TextLine) : First = False
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
答案 1 :(得分:1)
你可以在没有2个独立读者的情况下完成,因为你已经有了可用的价值。
Dim objReader As New System.IO.StreamReader(filename)
Dim lineCount as Integer 'lines read so far in file
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
If lineCount = 0 Then msgbox(TextLine) 'will show msgbox in first iteration
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
lineCount = lineCount + 1 'increment lineCount
Loop
答案 2 :(得分:0)
我已经为这个编写了一个工作代码,这里是:
Dim msgboxReader As New System.IO.StreamReader(filename)
msgbox(msgboxReader.ReadLine())
Dim objReader As New System.IO.StreamReader(filename)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
<强>更新强> 我只是宣布另一位读者只阅读第一行
答案 3 :(得分:0)
这段代码对我来说很好(但是,长文件可能会很慢)。
'' fileToOpen is the var with address of file (E.g.: c:\txt.txt)
Dim lineOneFromFile As String = IO.File.ReadAllLines(fileToOpen)(0)