0

For a project I'm doing I have to steamread a file into a list box. I dont know if my path is right because the explore path bar on top of my explore start menu isnt showing up. Can anyone tell me if my logic looks right and then help me to get somthing to find the path to my file.

Private Sub lstProducts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstProducts.SelectedIndexChange
        Dim reader As IO.StreamReader = Nothing
        Try
            reader = New IO.StreamReader("C:\OrdersFile.txt")
            While (reader.Peek <> -1)
                Me.lstProducts.Items.Add(reader.ReadLine())
            End While
        Catch ex As IO.FileNotFoundException
            MessageBox.Show("Error: File not found!")
        End Try
        reader.Close()
    End Sub
End Class
2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by waynespangler
0

As with any program written there is 101 ways to do the same thing. This is mine.
Define FileName outside the function as:

Private FileName As String = "C:\Test.txt"

1. If you are using vb 2002 or 2003

Try
            Dim Reader As New IO.StreamReader(FileName)
            lstAnimals.Items.AddRange(Split(Reader.ReadToEnd, vbCrLf))
            lstAnimals.SelectedIndex = 0
            Reader.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error in Reading file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

2. If you are using vb 2005

Try
            lstAnimals.Items.AddRange(Split(My.Computer.FileSystem.ReadAllText(FileName), vbCrLf))
            lstAnimals.SelectedIndex = 0
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error in Reading file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

3. The above 2005 code can be broken down to this if it helps to understand.

Try
            Dim str As String = My.Computer.FileSystem.ReadAllText(FileName)
            Dim ary() As String = Split(str, vbNewLine)
            lstAnimals.Items.AddRange(ary)
            lstAnimals.SelectedIndex = 0
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error in Reading file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

The 2002/2003 code will also work in 2005.

As for the file, your program must know where it is. You can try the search in explorer or write one of your own.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.