Search code examples
vb.netopenfiledialog

VB.NET get file name of selected file in OpenFileDialog - no path


I'm using the OpenFileDialog to open an Excel workbook, pass data from that workbook to another workbook, and then close the workbook I opened via OpenFileDialog. My problem is passing the data...how do I obtain just the name of the file I've opened via OpenFileDialog? I can't have the path, I just need the name of the file with it's extension. Here's part of my code

Dim filedialog As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
                filedialog.Title = "Open File Dialog"
                filedialog.InitialDirectory = "W:\TOM\ERIC\NET Dev"
                filedialog.RestoreDirectory = True
                If filedialog.ShowDialog() = DialogResult.OK Then
                    strFileName = filedialog.FileName
                    System.Diagnostics.Process.Start(strFileName)
                    StatVar.xlApp.Workbooks(StatVar.workbookName).Sheets("Input Form     Info").Range("B4:B204").Value = StatVar.xlApp.Workbooks(strFileName).Sheets("DJA Corp     Use").Range("C2:C202").Value
                    StatVar.xlApp.Workbooks(strFileName).Close(False)
                End If
            Else
                Exit Sub
            End If

I can't pass my data from workbook to workbook because the strFileName variable contains the file path. I've been trying to work with this function to return the file name but I'm not experienced enough apparently. Any help is appreciated.

    Public Function FileNameWithoutPath(ByVal FullPath As String) As String

    Return System.IO.Path.GetFileName(FullPath).ToString

    End Function

Solution

  • You can try filedialog.SafeFileName

    Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

    MSDN link