在VB(Visual Basic)中打开文件的方法有多种,以下是几种常用的方式:
方法一:使用CommonDialog控件
添加部件
单击菜单“工程”->“部件”,在弹出的“部件”对话框中找到并选中“Microsoft RichText Box 6.0”和“Microsoft Common Dialog 6.0”,然后单击“确定”按钮。
绘制控件
在窗体上绘制一个RichTextBox控件和一个CommonDialog控件。
编写代码
为打开文件按钮添加`open_Click`事件处理程序,设置CommonDialog控件的Filter属性以显示文本文件类型,然后调用ShowOpen方法打开文件,并将文件内容加载到RichTextBox控件中。
```vb
Private Sub open_Click()
CommonDialog1.Filter = "文本文件 (*.txt)|*.txt|(*.doc)|*.doc|所有文件|*.*"
CommonDialog1.ShowOpen
RichTextBox1.Text = "" ' 清空文本框
FileName = CommonDialog1.FileName
RichTextBox1.LoadFile FileName
Me.Caption = "超级记事本:" & FileName
End Sub
```
方法二:使用Binary方式读取文件
声明定长字符串变量
使用定长字符串变量(String * 65400)来读取文件内容,因为定长字符串变量支持的最大下界为65400字节,适合读取小于或等于32KB的文件。
```vb
Dim sA As String * 65400
Open "F:\d.txt" For Binary As 1
Get 1, , sA
Text1 = sA
Close 1
```
声明字符串变量并使用空格填充
声明一个字符串变量,然后用空格填充字符串,使其大小与文件大小一致,再通过Get语句将文件全部数据存储到变量中。
```vb
Dim sA As String
sA = Space(LOF(1))
Open "F:\d.txt" For Binary As 1
Get 1, , sA
RichTextBox1.Text = sA
Close 1
```
方法三:使用GetOpenFileName API函数
引用Microsoft Shell Controls And Automation
使用GetOpenFileName函数可以打开任意后缀名的文件,并且工作效率比控件高。
```vb
Dim swApp As Object
Dim Part As Object
On Error Resume Next
Set swApp = GetObject("SldWorks.Application")
If Err Then Err.Clear
Set swApp = CreateObject("SldWorks.Application")
Set Part = swApp.ActiveDoc
swApp.Visible = True
swApp.UserControl = True
On Error GoTo 0
Dim objFSO As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\path\to\file.txt")
Set Part = swApp.OpenDoc(objFSO.GetAbsolutePathName(objFile), 1)
Set Part = swApp.ActivateDoc(objFile.Name)
```
方法四:使用FileSystemObject对象的OpenTextFile方法
创建FileSystemObject对象
使用CreateObject函数创建一个FileSystemObject对象。
打开文件
使用OpenTextFile方法打开指定文件,并使用Do While循环读取文件内容,直到文件结束。
```vb
Dim fs As Object
Dim file As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set file = fs.OpenTextFile("C:\path\to\file.txt", 1)
Do While Not file.AtEndOfStream
MsgBox file.ReadLine
Loop
file.Close
Set file = Nothing
Set fs = Nothing
```
方法五:使用Dir函数和Open函数
列出文件
使用Dir函数列出指定目录下的所有文件,然后使用Open函数逐个打开文件。