【问题标题】:OpenFileDialog unhandled exceptionOpenFileDialog 未处理的异常
【发布时间】:2016-06-02 13:52:20
【问题描述】:

我正在使用模块中的OpenFileDialog 在 VS2013 中工作,它曾经很好用。如果用户再次打开它,则会显示此错误:

"ArgumentException 未处理

“System.ArgumentException”类型的未处理异常发生在 System.Windows.Forms.dll

附加信息:预计长度为正数"

我的代码:

Dim fd As OpenFileDialog = New OpenFileDialog()
Try
    With fd
        .Title = "Select File Dialog"
        .InitialDirectory = str_PathFileName
        .FileName = Path.GetFileName(str_PathFileName)
        .Filter = "All files (*.*)|*.*"
        .Multiselect = False
        .RestoreDirectory = True
        If (.ShowDialog() = DialogResult.OK) Then
        ...

错误发生在ShowDialog 行。我错过了什么?

【问题讨论】:

  • 崩溃时str_PathFileName的值是多少?异常对话框的详细信息中可能还有更多信息
  • 在 showdialog 返回后处理 openfiledialog
  • 添加 fd.Dispose() 没有效果
  • str_PathFileName 在第二次使用时包含有效的路径和文件名。
  • 如果我注释掉除 ShowDialog 之外的所有 OpenFileDialog 参数,我仍然得到错误:

标签: vb.net openfiledialog


【解决方案1】:

您的变量名 str_PathFileName 可能为空。检查您的路径是否良好。

           Dim fd As OpenFileDialog = New OpenFileDialog()
            Dim str_PathFileName As String = "C:\"  'put your valid path

            With fd
                    .Title = "Select File Dialog"
                    .InitialDirectory = str_PathFileName
                    .FileName = IO.Path.GetFileName(str_PathFileName)
                    .Filter = "All files (*.*)|*.*"
                    .Multiselect = False
                    .RestoreDirectory = True
                    If (.ShowDialog() = DialogResult.OK) Then

                    End If

                End With

这应该通过

【讨论】:

  • Your variable name str_PathFileName might be empty 这应该是评论,而不是答案,因为您发布的代码是相同的并且没有解决任何差异。因此,此时代码根本不是相对的。
  • @Terabithia 也许您的路径在打开时第二次被删除。在第二次尝试时使用调试检查路径。
  • 我已经确认第二次使用的路径是有效的,默认和第一次使用的路径相同。
【解决方案2】:

你的代码在一个简单的 Sub() 中对我来说很好,只包含你的代码 - 尝试将你的代码移动到按钮单击事件中,看看它是否停止失败。

这里有一个变体,可能会更好地清理一些东西:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim str_PathFileName As String = "C:\Temp"  'put your valid path
    Using fd As New OpenFileDialog
        With fd
            .Title = "Select File Dialog"
            .InitialDirectory = str_PathFileName
            .FileName = IO.Path.GetFileName(str_PathFileName)
            .Filter = "All files (*.*)|*.*"
            .Multiselect = False
            .RestoreDirectory = True
            Dim result As DialogResult = .ShowDialog
            MsgBox(result.ToString)
        End With
    End Using
End Sub

【讨论】:

  • 不幸的是,在这个应用程序中没有可以使用的按钮,OpenFileDialog 是由应用程序而不是用户启动的。
  • 我建议使用 Button_Click 作为一种隔离代码的方法,以查看您的程序中是否存在其他干扰。您正在构建控制台应用程序吗? WinForm,WPF? ??
猜你喜欢
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
相关资源
最近更新 更多