OpenFileDialog和InitialDirectory属性的问题

时间:2019-03-18 13:03:18

标签: vb.net winforms visual-studio-2017

我有两个Buttons和两个OpenFileDialog,并且遇到InitialDirectory属性的问题。当我为我的第一个OpenFileDialog选择一个文件,然后单击以为我的第二个OpenFileDialog选择一个文件时,我得到的是相同的InitialDirectory而不是我设置的文件! >

这是我的代码示例...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim FileDialog As New OpenFileDialog
        Dim Path As String = Nothing

        If Label1.Text IsNot Nothing And My.Computer.FileSystem.FileExists(Label1.Text) Then
            Path = Label1.Text
        Else
            Path = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
        End If

        FileDialog.Title = "Open File Dialog"
        FileDialog.InitialDirectory = Path
        FileDialog.Filter = "Executable (*.exe)|*.exe"
        FileDialog.RestoreDirectory = True

        If FileDialog.ShowDialog() = DialogResult.OK Then
            Label1.Text = FileDialog.FileName
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim FileDialog As New OpenFileDialog
        Dim Path As String = Nothing

        If Label2.Text IsNot Nothing And My.Computer.FileSystem.FileExists(Label2.Text) Then
            Path = Label2.Text
        Else
            Path = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
        End If

        FileDialog.Title = "Open File Dialog"
        FileDialog.InitialDirectory = Path
        FileDialog.Filter = "Executable (*.exe)|*.exe"
        FileDialog.RestoreDirectory = True

        If FileDialog.ShowDialog() = DialogResult.OK Then
            Label2.Text = FileDialog.FileName
        End If
    End Sub

1 个答案:

答案 0 :(得分:0)

好吧,我发现了什么问题...

我只需要像这样Path而不是像这样Path = IO.Path.GetDirectoryName(Label1.Text)那样设置Path = Label1.Text变量。因为第一个获取文件的目录路径(这是必需的),第二个获取文件的路径。我正在使用第二个...