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

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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值