PDA

View Full Version : Problem Opening and Reading Text File



jspattavina
09-13-2010, 02:32 PM
I am using the following code to Open a dialog box and let the user select a text file. Then get the file name and open a text file, read the contents to a string (mStr) and then write the string to a textbox (fText). It works for some text files but not others. For example the file "ARE_Journals.ris" opens fine and I can read the data. The file "ARE_MPEG Compression.ris" does not open and read?. Both files can be opened in a text editor and appear to be the similar (structure and line endings etc.).
Can anyone tell me what is wrong?
CODE:
----------------------------------------------------------
With ActiveDocument
mStr = ""
'Get filename
With Application.Dialogs(wdDialogFileOpen)
.Display
sFileName = .Name
End With
'Prepend path to Filename
sFile = ThisDocument.path & "\" & sFileName
'OpenFile
Dim iFile As Integer
On Local Error Resume Next
'Use FreeFile to supply a file number that is not already in use
iFile = FreeFile
Open sFile For Input As #iFile
'Read the whole content of the file to the string called mStr
mStr = Input$(LOF(iFile), iFile)
Close #iFile
'Write the Str to a TextBox called fText
fText.Text = mStr
End With

Sebastian H
10-21-2010, 05:43 PM
Your problem is that sFilename comes with parentheses, when there is a space in the file name. Therefore, before prepending the path to the filename, you need to do the following:

If Left(sFilename, 1) = """" Then
sFilename = Mid(sFilename, 2, Len(sFilename) - 2)
End If

jspattavina
10-22-2010, 07:17 AM
Thank you !!

Sebastian H
10-22-2010, 12:56 PM
You're welcome! BTW, I meant quotes, not parentheses, obviously.