vb.net StreamReader 找不到文件结尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28820163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:50:46  来源:igfitidea点击:

StreamReader not finding end of file

vb.netstreamreader

提问by John

I simply need to read lines from a text file and show them. When I run this I can see that id does what I want, but after it reads the last value it just shows a blank form on my screen and does not move on. It seems like it can't find the end of the file or something. I don't get an error.

我只需要从文本文件中读取行并显示它们。当我运行它时,我可以看到 id 做了我想要的,但是在它读取最后一个值后,它只在我的屏幕上显示一个空白表单并且不会继续。它似乎无法找到文件的末尾或其他东西。我没有收到错误。

Using sr As New System.IO.StreamReader(Application.StartupPath & "\myfile.cfg")
    Dim Line As String = ""
    Dim i As Integer = 0
    Dim temp_array As Array
    Do While Line IsNot Nothing
         Line = sr.ReadLine
         temp_array = Line.Split("=")
        'MessageBox.Show(temp_array(0))
    Loop


End Using

回答by jmcilhinney

That is bad code because you're actually going to use Linebefore testing whether it's Nothing. Here are two good options for looping through the lines of a text file:

那是糟糕的代码,因为Line在测试它是否为Nothing. 以下是循环文本文件各行的两个不错的选择:

Using reader As New StreamReader(filePath)
    Dim line As String

    Do Until reader.EndOfStream
        line = reader.ReadLine()

        '...
    Loop
End Using

For Each line In File.ReadLines(filePath)
    '...
Next

As you can see, the second is far more concise but it does require .NET 4.0 or later.

如您所见,第二个要简洁得多,但它确实需要 .NET 4.0 或更高版本。