Tuesday, May 24, 2011

Open a text file and read the contents line by line.

As written this needs to be run with a PCB file active.

Sub ReadTextFile

'Constants for File Handling
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TristateUseDefault = -2
Const TristateTrue = -1
Const TristateFalse = 0
Dim Board
Dim FileName
Dim oFS
Dim oFile
Dim oStream

Set Board = PCBServer.GetCurrentPCBBoard
If Board is Nothing Then Exit Sub

'File Handling - Place a text file named "TextFile.txt" in
'the same directory as the current board that is open.
FileName=Left(Board.FileName, InstrRev(Board.FileName, "\") ) & "TextFile.txt"

'Check for the text file
If Not FileExists(FileName) Then
   ShowMessage ( FileName & " was not found.")
   Exit Sub
End If
Set oFS = CreateObject("Scripting.FileSystemObject")
Set oFile = oFS.GetFile(FileName)
Set oStream = oFile.OpenAsTextStream(ForReading, TristateUseDefault)

I = 1
'Read the file in
Do While Not oStream.AtEndOfStream
      sRecord = oStream.ReadLine
      ShowMessage ( "Line #" & I & " " & sRecord )
      I = I + 1
Loop
oStream.Close

End Sub


www.tdpcb.com