我需要从文本文件中读取数据并在我的应用程序中使用它。我使用VB 6.0。 我使用什么命令?一些示例代码将受到高度赞赏。
答案 0 :(得分:15)
以下是如何从VB6 manual将整个文本文件读入字符串。
Function FileToString(strFilename As String) As String
iFile = FreeFile
Open strFilename For Input As #iFile
FileToString = StrConv(InputB(LOF(iFile), iFile), vbUnicode)
Close #iFile
End Function
答案 1 :(得分:11)
可以找到完整的教程和示例代码here
Open Filename$ For Input As #FileHandle
Do While Not EOF(FileHandle) ' Loop until end of file
Line Input #FileHandle, TextLine$ ' Read line into variable
' Your code here
Loop
Close #FileHandle
答案 2 :(得分:3)
我这里的游戏有点晚了,但是作为Microsoft Scripting Runtime(scrrun.dll)一部分的FileSystemObject对此非常有用。
Public Function ReadTextFileAsString(IN_sFilePath As String) As String
Dim myFSO As Scripting.FileSystemObject
Dim myTextStream As Scripting.TextStream
Dim myString As String
'Create a new FileSystemObject
Set myFSO = New Scripting.FileSystemObject
'Make sure file exists:
If myFSO.FileExists(IN_sFilePath) Then
Set myTextStream = myFSO.OpenTextFile(IN_sFilePath, ForReading)
myString = myTextStream.ReadAll()
Call myTextStream.Close
End If
'Assign Return Value
ReadTextFileAsString = myString
'Make sure to clean up when done.
Set myTextStream = Nothing
Set myFSO = Nothing
End Function
还有许多其他方法可用于从文本流中获取数据。您也可以一次读取一定数量的字符,也可以逐行读取。您需要将Microsoft Scripting Runtime添加到项目引用中,但它确实非常有用。
答案 3 :(得分:1)
确保您的文件存在:
If myFSO.FileExists(IN_sFilePath) Then
Set myTextStream = myFSO.OpenTextFile(IN_sFilePath, ForReading)
myString = myTextStream.ReadAll()
Call myTextStream.Close
End If
'Assign Return Value
ReadTextFileAsString = myString
答案 4 :(得分:0)
如果文件中只有纯文本,那么您可以使用以下代码将整个读入1个字符串变量:
Private Sub ReadFile(strFile As String)
Dim intFile As Integer
Dim strData As String
intFile = FreeFile
Open strFile For Input As #intFile
strData = Input(LOF(intFile), #intFile)
Close #intFile
End Sub
可变长度字符串最多可包含大约20亿(2 ^ 31)个字符
答案 5 :(得分:0)
以下是
的代码Function ReadFileToText(filePath)
Dim objFile, objText, text
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objText = objFile.OpenTextFile(filePath)
text = objText.ReadAll
objText.Close
Set objText = Nothing
Set objFile = Nothing
ReadFileToText = text
End Function
的详细信息
答案 6 :(得分:-1)
我将推荐一种不同的方法来阅读并将内容导入到表单窗口
public sub readfile
Dim rtc As TextBox = New TextBox
rtc.Multiline = True
rtc.ScrollBars = ScrollBars.Both
rtc.Width = 400
rtc.Height = 200
Me.Controls.Add(rtc)
rtc.WordWrap = True
Dim FILE_NAME As String = "C:\Users\vcidex92\Desktop\suji\me.html"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
rtc.Text = objReader.ReadToEnd
objReader.Close()
Else
MsgBox("File Does Not Exist")
End If
end sub