Search code examples
vb.netstringpathstring-concatenationfolderbrowserdialog

Why am I getting an inconsistent path format with FolderBrowserDialog.SelectedPath method?


I keep getting an inconsistent path format with the FolderBrowserDialog.SelectedPath method, more specifically the path returned seems to be randomly missing or having the trailing backslash, this is causing problems for me for the following line of code

xlWorkSheet.SaveAs(Filename:=dialog.SelectedPath & "Excel_Export_" & dt.ToString("ddMMMyyyy") & ".xlsm", FileFormat:=52)

Any help would be great thanks.


Solution

  • Path.Combine() will help you construct a valid, fully qualified filename. Rather than trying to squeeze everything into a one liner:

    Dim xFil As String = "Excel_Export_" & dt.ToString("ddMMMyyyy") & ".xlsm"
    xFil = Path.Combine(dlg.SelectedPath, xFil)
    xlWorkSheet.SaveAs(Filename:= xFil, FileFormat:= 52)
    

    If the files were going into folders bearing the date (which is what your code looked like at first glance), the date string would be one of the folder args:

    Dim xFil As String = "Sales_" & dt.ToString("MMyyyy") & ".xlsm"
    xFil = Path.Combine(dlg.SelectedPath, dt.ToString("ddMMMyyyy"), xFil)
    xlWorkSheet.SaveAs(Filename:= xFil, FileFormat:= 52)
    

    The point is, Path.Combine() wont ever miss a directory separator or add an extra one.