您的位置:首页 > 编程语言 > VB

vb 多级路径创建,读取文件或文件夹[vb类写法]

2014-12-22 19:24 453 查看
1.创建一个类,命名为:myfile ,复制下面代码进去

'判断文件是否存在
Public Function isFileExis(path As String) As Boolean

If Dir(path, vbDirectory) = "" Then
'不存在
isFileExis = False
Else
'存在
isFileExis = True
End If

End Function
'作用:根据路径逐级创建文件夹
'参数: path 路径 f:\文件夹a\文件夹b
'返回: 无;
Public Function createFolder(path As String)  'C:\Users\Administrator\Desktop\类操作   '\\A352337697\d\My Documents
Dim arr, a, temPath As String, n
arr = Split(path, "\")
For a = 0 To UBound(arr)
temPath = temPath & arr(a) & "\"
If Len(arr(a)) > 0 Then
n = n + 1
If n > 1 Then
'MsgBox temPath & "_________" & isFileExis(temPath)
If isFileExis(temPath) = False Then
MkDir temPath
End If
End If
End If
Next a
End Function
'作用: 写入文件内容,如果文件不存在,则逐级创建出路径,直到创建此路径的文件,再写入
Public Function writeFile(path As String, content As String)

'MsgBox path
'//取得文件所在路径
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夹路径
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
'//写入
Open path For Output As #1
Print #1, content;
Close #1

End Function

'作用: 写入文件内容,如果文件不存在,则逐级创建出路径,直到创建此路径的文件,再写入
Public Function writeFileAppend(path As String, content As String)

'MsgBox path
'//取得文件所在路径
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夹路径
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
'//写入
Open path For Append As #1
Print #1, content;
Close #1

End Function

'作用: 读取文件内容,如果文件不存在,则逐级创建出路径,直到创建此路径的文件,再读取
'参数:path
'返回:文件内容;
Public Function readFile(path As String)

'MsgBox path
'//取得文件所在路径
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夹路径
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
Open path For Output As #1
Print #1, "";
Close #1
'//读取
Open path For Input As #1
readFile = StrConv(InputB$(LOF(1), 1), vbUnicode)
Close #1

End Function


2.然后可以这样调用

Private Sub Command1_Click()
    Dim ff As myfile '搜索'声明类
    Set ff = New myfile '实例化..这样就可以使用这个类了

    Call ff.writeFileAppend("f:\临时文件夹\真的吗\不要紧吧.txt", "真的吗") '调用这个实例的方法
    Set ff = Nothing '释放对象
End Sub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: