新建From1(窗体),新建Command1(按钮CommandButton),代码:
Public Function f_ReadText(strFN$) As String
'读取文本
Dim intFileNum%: intFileNum = FreeFile
If Dir(strFN) <> "" Then
Open strFN For Binary As #intFileNum
f_ReadText = StrConv(InputB(LOF(intFileNum), 1), vbUnicode)
Close #intFileNum
Else
f_ReadText = ""
End If
End Function
Public Function f_SaveText(strFN$, ByVal strAll$) As Long
'保存文本
On Error GoTo hErr
Dim intFileNum%: intFileNum = FreeFile
Open strFN For Output As #intFileNum
Print #intFileNum, strAll
Close #intFileNum
f_SaveText = 0 '返回0
Exit Function
hErr:
f_SaveText = Err.Number '返回错误编号
End Function
Public Function f_ReadBin(strFN$, Optional ByVal lngStartPos& = 1, Optional ByVal lngFileSize& = -1) As Byte()
'二进制方式读取到数组
Dim intFileNum%: intFileNum = FreeFile
If Dir(strFN) <> "" Then
Open strFN For Binary As #intFileNum
If lngFileSize = -1 Then
ReDim f_ReadBin(LOF(intFileNum) - lngStartPos)
Else
ReDim f_ReadBin(lngFileSize - 1)
End If
Get #intFileNum, lngStartPos, f_ReadBin
Close #intFileNum
End If
End Function
Public Function f_SaveBin(strFN$, bytData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True) As Long
'二进制方式写入到数组
On Error GoTo hErr
Dim intFileNum%: intFileNum = FreeFile
If OverWrite = True And Dir(strFN) <> "" Then
Kill strFN
End If
Open strFN For Binary As #intFileNum
If lngStartPos = -1 Then
Put #intFileNum, LOF(intFileNum) + 1, bytData
Else
Put #intFileNum, lngStartPos, bytData
End If
Close #intFileNum
f_SaveBin = 0 '返回0
Exit Function
hErr:
f_SaveBin = Err.Number '返回错误编号
End Function
Private Sub Command1_Click()
Dim strFN$
strFN = App.Path & "\manongku.txt"
Debug.Print f_ReadText(strFN)
End Sub
运行结果(记得\manongku.txt需要ANSI编码哦):
MaNongKu.com
码农库
东西好呀,
真的好!