Question

I have a textbox that will be populated with a directory structure (for example, C:\Program Files\Visual Basic). I'm trying to use the textbox.text object in another variable, but when the path includes spaces the information will cut off.

Here is the offending code that populates the text box with the path:

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

Note that it uses FolderBrowserDialog to populate the text box, and this part works fine. I have another button click that then uses the textbox.text along with a specific file name within a function I defined elsewhere:

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

It's never getting far enough to parse the file name, the exception is:

    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."
Was it helpful?

Solution

Your first button handler should check the result of 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

Your second handler should use 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

*It should probably check to make sure the path actually exists as well!

What does RunScript() do?

Sometimes applications require that paths with spaces be enclosed in quotation marks:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top