Text File as a string?
Posted on 2006-06-07
I am using the code (below) to read a textfile into a variable called sDetailFormScript. There are 2 strings buried within the text file and I want extract everything between those two strings (and truncate everything before the first string occurence and truncate everything after the second string occurence). I was looking for something as simple as an InStr function to identify the starting and ending character positions within the text file (the strings are unique by definition). However, I believe InStr will not tolerate a vbCRLF as a character within a string(?) - and since this is a text file, I suspect that InStr will only function on a line by line basis (I am assuming here).
My question: is there a way for me to treat a text file as a string (instead of multiple lines) so that I can do string manipulation on the file using character positions? (One thought is converting the vbCRLF characters within sDetailFormScript - if they are indeed the obstacle to using InStr - to some unique string, then do the string manipulations, then convert those unique strings back to vbCRLF).
I was trying to avoid processing the text file one row at a time... so I would appreciate if anyone has ideas on how I can accomplish what I have described.
The code I am using to load the text file as a string into sDetailFormScript:
filename = "c:\sample.txt"
sDetailFormScript = FileText( filename)
Function FileText(ByVal filename As String) As String
'UPDATE: Andrew Marshall wrote us to point out that the above routine fails when the file includes a Ctrl-Z (EOF) character, so we prepared a better version that works around that problem:
Dim handle As Integer
' ensure that the file exists
If Len(Dir$(filename)) = 0 Then
Err.Raise 53 ' File not found
' open in binary mode
handle = FreeFile
Open filename$ For Binary As #handle
' read the string and close the file
FileText = Space$(LOF(handle))
Get #handle, , FileText