elenorcoli opened this issue on Mar 15, 2007 · 4 posts
elenorcoli posted Thu, 15 March 2007 at 1:06 AM
sorry guys i know this place is about python, but i figure if you all know that you're probably pretty good at basic.
my question is about visual basic. i am attempting to read from text file line by line. i'm new at this but working hard on picking it up. the only example i have seen comes from http://www.homeandlearn.co.uk/NET/vbNet.html
an otherwise decent place. but their example is wrong. it seems like they chose the right method, but something just doesn't work out. here is the code:
Dim FILE_NAME As String = "C:test.txt"
Dim TextLine As String
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = TextLine & objReader.ReadLine() & vbNewLine
Loop
Textbox1.Text = TextLine
Else
MsgBox("File Does Not Exist")
End If
i've been hacking on this for hours and all over the net, just can't get a solution. this code reads the entire text, without going line by line.
so anyone have any ideas? or any favorite websights that could help in visual basic?
mucho gracias
adp001 posted Thu, 15 March 2007 at 1:48 AM
Aren't such simple problems used as samples in the docu?
Dim TextLine as String
Dim TextBlock as String
...
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextBlock = TextBlock & TextLine & vbNewLine
Loop
...
Now each line is first read into TextLine. You may change the content of TextLine to your needs before it is appended to TextBlock (Textblock is now what TextLine was - variable names should reflect what happens).
Or remove the line completly where the string is attached to TextBlock if you only check a file for something.
Not sure if obReader.Peek() is the best way to check for end of file. I'm not a Visual Basic Programmer. But I bet there is something other to check for EOF (do a search in your documentation for EOF).
Perhaps it's a better (faster) way to spend the time used to search ready to go script snippets with learning a bit about programming :)
svdl posted Thu, 15 March 2007 at 7:30 AM
The Reader objects all have an EOF marker, so you can change the code into
while not objReader.EOF() do
You can read alll the lines of a textfile into an array of strings, each string will represent one line:
Dim TextLines() as string
...
TextLines=objReader.ReadLines()
...
Maybe the text file is too big to hold in memory though.
As for favorite websites, the online help of VB.NET (I assume you're using the 2005 Express edition) usually gives a good start, for the rest there's www.gotdotnet.com
The pen is mightier than the sword. But if you literally want to have some impact, use a typewriter
elenorcoli posted Tue, 20 March 2007 at 10:37 AM
wow thanks much guys working on this now will check back with conclusion