我让这段Vb代码工作失踪了什么(VB 2005)

时间:2008-11-12 18:22:13

标签: vb.net

For Each line As String In System.IO.File.ReadAllLines("file.txt")
'Do Something'
Next

Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
    Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
            While Not s.EndOfStream
                    Dim line As String = s.ReadLine

                    'put you line processing code here

            End While
    End Using
End Using

都显示为红色,我正在运行一个干净安装的MS VS2005,这些代码都推荐给我,我错过了我需要安装或声明的其他内容吗?

3 个答案:

答案 0 :(得分:1)

从Msdn你应该执行以下操作来阅读所有行

Dim Lines As String()
Lines = System.IO.File.ReadAllLines("file.txt")

对于第二个例子,这样的事情可能会起作用

Dim sr as New StreamReader("somefile.txt")
Dim line as String = sr.ReadLine()
Do While Not line is Nothing
    line = sr.ReadLine()
    'do something else
Loop

我刚刚创建了以下VB.Net控制台应用程序,它运行正常:

Imports System.IO

Module Module1

Sub Main()
    Dim sr As New StreamReader("somefile.txt")
    Dim line As String = sr.ReadLine()
    Do While Not line Is Nothing
        line = sr.ReadLine()
        'do something else
    Loop

End Sub

End Module

答案 1 :(得分:1)

您的代码是否被类和方法所包围?

Public class CodeClass
    Public Sub CodeMethod

        Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
            Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
                While Not s.EndOfStream
                    Dim line As String = s.ReadLine

                    //Non-vb comment for easier to read SO code
                End While
            End Using
        End Using

    End Sub
End Class

答案 2 :(得分:0)

对于vb6.0,你需要

Dim value As String = My.Computer.FileSystem.ReadAllText(file)