vb 读写文本 注释+文本

'添加窗体Form1,文本框Text1,按钮Command1,Command2,然后添加如下代码:
Private Sub Form_Load()
Command1.Caption = "读文件"
Command2.Caption = "写文件"
End Sub

Private Sub Command1_Click() '读文件
Text1.Text = fileStr("C:\t1.txt")
MsgBox "读入完毕!"
End Sub

Private Sub Command2_Click() '写文件
writeToFile "C:\t1.txt", Text1.Text
MsgBox "写入完毕!"
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'功能:根据所给的文件名返回文件的内容
'函数名:fileStr
'入口参数(如下):
' strFileName 所给的文件名;
'返回值:文件的内容
'备注:sysdzw 于 2007-5-3 提供
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Function fileStr(ByVal strFileName As String) As String
On Error GoTo Err1
Dim tempInput As String
Open strFileName For Input As #1
Do While Not EOF(1)
Line Input #1, tempInput
If Right(tempInput, 1) <> Chr(10) Then tempInput = tempInput & Chr(10)
tempInput = Replace(tempInput, Chr(10), vbCrLf)
fileStr = fileStr & tempInput
Loop
If fileStr <> "" Then fileStr = Left(fileStr, Len(fileStr) - 2)
Close #1
Exit Function
Err1:
MsgBox "不存在该文件或该文件不能访问!", vbExclamation
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'功能:根据所给文件名和内容直接写文件
'函数名:writeToFile
'入口参数(如下):
' strFileName 所给的文件名;
' strContent 要输入到上述文件的字符串
'返回值:True或False,成功则返回前者,否则返回后者
'备注:sysdzw 于 2007-5-2 提供
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Function writeToFile(ByVal strFileName As String, ByVal strContent As String) As Boolean
On Error GoTo Err1
Open strFileName For Output As #1
Print #1, strContent
Close #1
writeToFile = True
Exit Function
Err1:
writeToFile = False
End Function

相关文档
最新文档