vb.net

Read a text file in VB


New Visual basic programmer here. Trying to get a textfile to be read by the program but it seems to simply not work, no error messages or anything. It just does not grab the values at all

The textfile name is exactly the same.

Public Sub ReadDef()

    Dim DefSR As IO.StreamReader = IO.File.OpenText("BikeDefault.txt")

    GlobalTotBikes = DefSR.ReadLine()
    GlobalRentRate = DefSR.ReadLine()
    GlobalHSTRate = DefSR.ReadLine()
    GlobalTourRate = DefSR.ReadLine()
    GlobalGPSRate = DefSR.ReadLine()
    GlobalInsurRate = DefSR.ReadLine()
    GlobalWaterBotRate = DefSR.ReadLine()
    GlobalNextBookNum = DefSR.ReadLine()
    GlobalNextCustNum = DefSR.ReadLine()
    GlobalNextInvoiceNum = DefSR.ReadLine()

    DefSR.Close()

End Sub

I've compared this code a bunch of times to the example I was given and I see nothing different.

Thanks.


Solution

  • Simple search on google http://www.dotnetperls.com/streamreader-vbnet

    Make 100% sure BikeDefault.txt exists. If you wish to make sure, copy the file over to the C:\ Drive to keep it simple and replace your BikeDefault.txt with "C:\\BikeDefault.txt"

    You can use the StreamReader like so:

    Imports System.IO
    
    Module Module1
    
        Sub Main()
        ' Store the line in this String.
        Dim line As String
        Dim FilePath As String = "C:\\BikeDefault.txt"
        ' Create new StreamReader instance with Using block.
        Using reader As StreamReader = New StreamReader(FilePath)
            ' Read one line from file
            line = reader.ReadLine
        End Using
    
        ' Write the line we read from "file.txt"
        Console.WriteLine(line)
        End Sub
    
    End Module
    

    Or keep it simple with File.ReadAllLines.

    For Each line As String In File.ReadLines("MyTextFile.txt")
        'Code here to read each line
    Next line