【问题标题】:Textbox text not parsing with spaces in VB.NET文本框文本在 VB.NET 中不使用空格进行解析
【发布时间】:2013-05-22 17:44:54
【问题描述】:

我有一个将用目录结构填充的文本框(例如,C:\Program Files\Visual Basic)。我正在尝试在另一个变量中使用 textbox.text 对象,但是当路径包含空格时,信息将被切断。

这是用路径填充文本框的违规代码:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles b_Script.Click
        Dim BrowseFolder As New FolderBrowserDialog
        BrowseFolder.ShowDialog()
        tbScript.Text = BrowseFolder.SelectedPath
    End Sub

请注意,它使用FolderBrowserDialog 填充文本框,这部分工作正常。我有另一个按钮单击,然后使用textbox.text 以及我在其他地方定义的函数中的特定文件名:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Path As String
        Path = tbScript.Text & "\Client_Perfmon.ps1"
        RunScript(Path)
    End Sub

解析文件名永远不够,例外是:

    Exception:Caught: "The term 'C:\Users\seanlon\Desktop\Performance\Powershell' is not
 recognized as the name of a cmdlet, function, script file, or operable program. Check the
 spelling of the name, or if a path was included, verify that the path is correct and try
 again." (System.Management.Automation.CommandNotFoundException)
    A System.Management.Automation.CommandNotFoundException was caught: "The term
 'C:\Users\seanlon\Desktop\Performance\Powershell' is not recognized as the name of a
 cmdlet, function, script file, or operable program. Check the spelling of the name, or if
 a path was included, verify that the path is correct and try again."

【问题讨论】:

  • 您的RunScript() 功能已损坏。

标签: vb.net folderbrowserdialog system.management


【解决方案1】:

您的第一个按钮处理程序应该检查 ShowDialog() 的结果:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles b_Script.Click
    Dim BrowseFolder As New FolderBrowserDialog
    If BrowseFolder.ShowDialog() = Windows.Forms.DialogResult.OK Then
        tbScript.Text = BrowseFolder.SelectedPath
    End If
End Sub

您的第二个处理程序应该使用 Path.Combine():

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Path As String = System.IO.Path.Combine(tbScript.Text, "Client_Perfmon.ps1")
    RunScript(Path)
End Sub

*它可能应该检查以确保路径确实存在!

RunScript() 有什么作用?

有时应用程序要求带空格的路径用引号引起来:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Path As String = Chr(34) & System.IO.Path.Combine(tbScript.Text, "Client_Perfmon.ps1") & Chr(34)
    RunScript(Path)
End Sub

【讨论】:

  • runscript() 抓取指定的文件(Powershell 脚本)并单独拉出每一行,将其放入字符串中(在适当的地方使用换行符)。为什么我需要检查 BrowseFolder.ShowDialog() 的结果?我理解检查,但这只是为了确保已使用有效目录吗?
  • "OK" 在用户实际选择文件时返回。如果他们取消对话框,您不会想要处理任何内容(不会有选定的文件!)。
  • 这对我来说很有意义,我添加了一个签入以确保文件的路径存在。代码仍然无法正常工作(即使文件存在,system.io.file.exists(Path) 也会返回 false),但这是另一个问题!
猜你喜欢
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多