Home
  ASP
  VB
  PHP
  Contact Us

 


Partners
Visual Basic News & Information Source


       

Reading from a text file

Okay Folks

This is not a big project but a very simple application just to show you how to read from a text file while remaining in the VB environment. The main function used in the code is Read_Files()

We have used the filesystemobject to open the text file saved on your hard disk, we have hardcoded the path in the code but you can prompt the user to enter the name of the file to be opened. To open the file use the getfile method of the filesystemobject and then use the openastextstream method to open the file and read the contents of the file by calling the readall method of the filesystemobject. You can read the special values stored in the text file. For example, you can store the name of the database, user id and password and then read the file to get these attributes from the file, this makes it easy to change the details of the database in the file instead of changing the code each time there is change in the database. Hope, this helps!!!!

CODE:

Option Explicit

Private Sub Form_Load()
Read_Files
End Sub
Sub Read_Files()
Dim fso As New FileSystemObject, txtfile, _
fil1 As File, ts As TextStream
Dim s As Variant

Set fil1 = fso.GetFile("d:\temp\test.txt")

Set ts = fil1.OpenAsTextStream(ForReading)
If Not ts.AtEndOfStream Then

's = ts.ReadLine
s = ts.ReadAll
Dim SearchString, SearchChar, MyPos
SearchString = s ' String to search in.
SearchChar = vbCrLf ' Search for "P".

' A textual comparison starting at position 4. Returns 6.
MyPos = InStr(1, SearchString, SearchChar, 1)

' A binary comparison starting at position 1. Returns 9.
'MyPos = InStr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (last argument is omitted).
'MyPos = InStr(SearchString, SearchChar) ' Returns 9.
Dim mypos2
mypos2 = InStr(MyPos + 1, SearchString, SearchChar)
'MyPos = InStr(1, SearchString, "W") ' Returns 0.
'MsgBox MyPos
Dim word As Variant
Dim i As Integer
'For i = 0 To MyPos
word = Mid(s, 1, MyPos - 1)

'Next i
'For i = MyPos + 1 To mypos2 - 1
'Next i
'MsgBox word
Dim word2
For i = MyPos + 2 To mypos2 - 1
word2 = word2 & Mid(s, i, 1)
Next i

' word = Mid(s, MyPos + 2,len(
MsgBox word
'MsgBox mypos2
MsgBox word2
End If
ts.Close
End Sub
   

 

 

 

    


 


 

Home | ASP | VB | PHP | Contact Us


© 2002 Wali Systems Inc.