打开一个文件,如何才能只得到文件名和扩展名,不需要他的绝对路径。怎样判断要打开的文件是否存在和文件的大小?

解决方案 »

  1.   

    //打开一个文件,如何才能只得到文件名和扩展名,不需要他的绝对路径。怎样判断要打开的文件是否存在和文件的大小?
    得到文件大小用vb提供的filelen函数就可以,如 msgbox filelen(文件路径)
    Private Function sfilename(ByVal fullpath As String) As String '得到带扩展名的文件名
        Dim temparr As Variant, getfilename As String
        temparr = Split(fullpath, "\")
        Dim i As Long
        i = UBound(temparr)
        Dim j As Long
        If i = 0 Then
            j = InStr(1, temparr(0), ":")
            If j = 0 Then
                getfilename = temparr(0)
            ElseIf j = 2 Then
                getfilename = Mid(temparr(0), 3, Len(temparr(0)) - 2)
            End If
        Else
            getfilename = temparr(i)
        End If
        Dim errstr As String, s As String
        errstr = "\/:*? <> |"""
        For i = 1 To Len(errstr)
            s = Mid(errstr, i, 1)
            If InStr(1, getfilename, s) > 0 Then
                MsgBox "所输入的文件名错误"
                sfilename = ""
                Exit Function
            End If
        Next
        sfilename = getfilename
    End Function
    Private Function sRightname(ByVal fullpath As String) As String '得到扩展名
        Dim temp As String
        temp = sfilename(fullpath)
        If temp = "" Then
            sRightname = ""
            Exit Function
        End If
        Dim arr As Variant
        arr = Split(temp, ".")
        If UBound(arr) = 0 Then
            sRightname = ""
            Exit Function
        End If
        sRightname = arr(UBound(arr))
    End Function
    Private Function sLeftname(ByVal fullpath As String) As String '得到不带扩展名的文件名
        Dim temp As String
        temp = sfilename(fullpath)
        If temp = "" Then
            sLeftname = ""
            Exit Function
        End If
        Dim arr As Variant
        arr = Split(temp, ".")
        If UBound(arr) = 0 Then
            sLeftname = arr(0)
            Exit Function
        Else
        Dim i As Long
            i = Len(arr(UBound(arr)))
            sLeftname = Left(temp, Len(temp) - i - 1)
        End If
    End Function
    Private Function filehave(ByVal fullpath As String) As Boolean '判断文件是否存在
        If Dir(fullpath) = "" Then ' 文件不存在
            filehave = False
        Else
            filehave = True
        End If
    End Function
    Private Sub Command1_Click()
        MsgBox sfilename("c:test.txt")
        MsgBox sfilename("c:\ss\test.txt")
        MsgBox sLeftname("c:\ss\aa\test.txt")
        MsgBox sLeftname("c:test.txt")
        MsgBox sRightname("c:\ss\aa\test.txt")
        MsgBox sRightname("c:test.txt")
        MsgBox filehave("c:\ss\aa\test.txt")
    End Sub