2016-08-15 40 views
0

我试图从一个VB.NET应用程序内运行目标相对路径。我已经确保使用反斜杠(而不是正斜杠),并且还要将工作目录设置为正确的源路径来运行Process;尝试运行时仍出现The system cannot find the file specified错误。在Windows中运行相对路径?

例如,我有(伪代码):

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

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

这里的小组到目前为止:

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 
+0

两点('..')表示一个目录级别比当前更高。一个点('.')表示当前目录。 – TnTinMn

+0

在此示例中,C:\ Windows \ notepad.exe是比C:\ Windows \ System32更高的一个目录级别。 –

回答

0

IO.Path.GetDirectoryName("C:\Windows\System32")返回“C :\视窗”;包含“C:\ Windows \ System32”的目录。

StartInfo.Filename = "..\notepad.exe"告诉过程在“C:\”中查找notepad.exe

此外,为此,您需要设置StartInfo.UseShellExecute = True;说明请参见:ProcessStartInfo Class

With pRun.StartInfo 
    .UseShellExecute = True 
    .WorkingDirectory = txtSource.Text.Trim 
    .FileName = txtResult.Text.Trim 
End With 
+0

啊哈!对于这个例子,我最初将txtSource设置为包含实际文件名的完整路径,但是在没有首先进行双重检查的情况下缩短了示例,但将'.UseShellExecute'设置为'True'是关键。当你每天花12个小时进行编码时,总会遇到那些你想念的小事,几天,大声笑。谢谢! –