flohdieter flohdieter - 5 months ago 37
Vb.net Question

VB - Concatenation of two String-variables fails

I try to concatenate two variables of type string, and my result is only the first variable:

Function newXlsx(ByVal sFilepath As String) As Boolean
Dim sFileName As String
Dim sTest As String

sTest = sFilepath.Trim()
sFileName = Format(Now, "yyyy-MM-dd") & ".xls*"
MsgBox(sTest & "\" & sFileName)

If My.Computer.FileSystem.FileExists(sFilepath & "\" & sFileName) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
End Function


Note:
sFilepath
given to the function is "H:\A74" with multiple spaces after the "4", thats why I
Trim()
the string. So
sTest
is "H:\A74" and
sFileName
is "2016-06-22.xls*" but the result is not "H:\A74\2016-06-22.xls*" how I would expect it, instead it is just "H:\A74".

Answer

Use System.IO.Path.Combine to prevent such issues:

Function newXlsx(ByVal sFilepath As String) As Boolean   
    Dim sFileName = Date.Now.ToString("yyyy-MM-dd") & ".xls"
    Dim path = System.IO.Path.Combine(sFilepath.Trim(), sFileName)    
    Dim exists = System.IO.File.Exists(path)
    If exists Then
        MsgBox("File found.")
    Else
        MsgBox("File not found.")
    End If
    Return exists
End Function

Note that you are using My.Computer.FileSystem.FileExists(sFilepath & "\" & sFileName) instead of your trimmed string.


Update: Maybe your path contains invalid characters. You could use a method to remove them:

ReadOnly InvalidPathChars As String = New String(Path.GetInvalidPathChars())

Public Function RemoveInvalidPathChars(dirOrFileName As String) As String
    dirOrFileName = dirOrFileName.Trim()
    For Each c As Char In InvalidPathChars
        dirOrFileName = dirOrFileName.Replace(c, "")
    Next
    Return dirOrFileName
End Function

Then change your method accordingly to use it:

Function newXlsx(ByVal sFilepath As String) As Boolean
    Dim sFileName = Date.Now.ToString("yyyy-MM-dd") & ".xls"
    Dim safePath = RemoveInvalidPathChars(sFilepath)
    Dim path = System.IO.Path.Combine(safePath, sFileName)
    Dim exists = System.IO.File.Exists(path)
    If exists Then
        MsgBox("File found.")
    Else
        MsgBox("File not found.")
    End If
    Return exists
End Function
Comments