我尝试连接两个string类型的变量,我的结果只是第一个变量:
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
注意:赋予该功能的sFilepath
是" H:\ A74"在" 4"之后有多个空格,这就是为什么我Trim()
字符串。所以sTest
是" H:\ A74"和sFileName
是" 2016-06-22.xls *"但结果不是" H:\ A74 \ 2016-06-22.xls *"我怎么期待它,而不仅仅是" H:\ A74"。
答案 0 :(得分:4)
使用System.IO.Path.Combine
来防止此类问题:
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
请注意,您使用的是My.Computer.FileSystem.FileExists(sFilepath & "\" & sFileName)
而不是修剪过的字符串。
更新:可能您的路径包含无效字符。您可以使用方法删除它们:
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
然后相应地更改您的方法以使用它:
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
答案 1 :(得分:0)
使用IO.Path方法
Function newXlsx(ByVal sFilepath As String) As Boolean
Dim spath As String
spath = IO.Path.Combine(sFilepath.Trim, DateTime.Now.ToString("yyyy-MM-dd"))
spath = IO.Path.ChangeExtension(spath, "xls")
MsgBox(spath)
If My.Computer.FileSystem.FileExists(spath) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
End Function