首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从vb.net中的txt文件中获取第一行

如何从vb.net中的txt文件中获取第一行
EN

Stack Overflow用户
提问于 2013-09-19 05:14:42
回答 4查看 7.2K关注 0票数 0

这是我读取txtfile并将其放入datagridview的代码。

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
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

现在我只想获得我的put文件的第一条记录,并把它放在msgbox中,我如何做到这一点?

我试过这个:

代码语言:javascript
复制
MsgBox(SplitLine.tostring)

但是这段代码的输出是:System.String[]

谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-09-19 05:47:46

您可以在没有两个单独的读取器的情况下这样做,因为您已经有了可用的值。

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2013-09-19 05:39:53

首先为布尔值= True

按如下方式编辑循环:

代码语言:javascript
复制
Do While objReader.Peek() <> -1
    TextLine = objReader.ReadLine()
    If First Then MessageBox(TextLine) : First = False
    SplitLine = Split(TextLine, ",")
    dvList.Rows.Add(SplitLine)
Loop
票数 1
EN

Stack Overflow用户

发布于 2013-09-19 05:27:04

我已经为这个代码编写了一个工作代码,如下所示:

代码语言:javascript
复制
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

更新我只是声明另一个读取器只读第一行

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18886650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档