Question Run a Relative Path in Windows?

GeekDrop

Well-known member
Joined
Dec 14, 2006
Messages
161
Location
Chicago
Programming Experience
10+
I'm attempting to run a destination relative path from within a VB.NET app. I've made sure to use backslashes (rather than forward slashes), and also running the Process with the working directory set to the correct source path; still getting a The system cannot find the file specified error when trying to run it.

For example, I have (pseudo-code):

txtSource.text path = "C:\Windows\System32"

txtResult.text path = "..\notepad.exe"

Here's the Sub so far:

Code:
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click

    Try

        ' Create the process object
        Dim pRun As New Process()

        ' Set it to run from the Source folder (Working Directory)
        With pRun.StartInfo
            .UseShellExecute = False
            .WorkingDirectory = IO.Path.GetDirectoryName(txtSource.Text.Trim)
            .FileName = txtResult.Text.Trim
        End With

        pRun.Start()

        ' Wait for it to finish
        pRun.WaitForExit()

    Catch ex As Exception

        Debug.Print(ex.Message)

    End Try

End Sub
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,412
Location
Norway
Programming Experience
10+
ProcessStartInfo.WorkingDirectory Property (System.Diagnostics)
When UseShellExecute is false, the WorkingDirectory property is not used to find the executable. Instead, its value applies to the process that is started and only has meaning within the context of the new process.
As a consequence, the Process uses current directory, and your filename will be relative to that.

So what if UseShellExecute is true? What WorkingDirectory are you actually setting when you use GetDirectoryName? Is Notepad.exe in the relative parent to that? Path.GetDirectoryName Method (String) (System.IO)
 

GeekDrop

Well-known member
Joined
Dec 14, 2006
Messages
161
Location
Chicago
Programming Experience
10+
Aha! For the example I originally had txtSource set to a full path including an actual file name, but shortened it for the example without double-checking first, lol, but setting .UseShellExecute to True was the key.

It's always those little things you miss when you've spent 12 hours a day coding, for days, lol. Thanks!

Btw, glad to see you're still around the forum after all these years, JohnH. =)
 
Top Bottom