vb.net How to pass a string with spaces to the command line

后端 未结 6 1753
轻奢々
轻奢々 2020-12-11 23:02

I am trying to call an external program using Process:

    Dim strExe As String = \"E:\\Projects\\Common Files\\mktorrent.exe\"
    Dim p As New Process
             


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 23:12

    Windows does not provide a common way of keeping arguments with spaces as single arguments. However there are a number of relatively common standards that you've tried.

    So it comes down to either determining what argument processing mktorrent.exe uses or, as you're trying to pass a filename, using "MSDOS" 8.3 format for the path which will have no spaces.

    For the latter, this answer points to the Win32API GetShortPathName.

    Of course, 8.3 filenames can be disabled with modern Windows (all Windows NT-based systems I believe -- not that it often is). So your only full solution is to determine what argument processing mktorrent supplies.

    Since your comment suggesting the quotes are not being passed through I confirmed I see 'testing' 'testing' '1 2 3' in the MsgBox output of this vbscript:

    Option Explicit
    
    Dim arg
    Dim line
    
    For Each arg in WScript.Arguments
      line = line & " '" & arg & "'"
    Next
    
    MsgBox Trim(line)
    

    when executed using:

    Dim strExe As String = "C:\Windows\System32\wscript.exe"
    Dim p As New Process
    Dim pinfo As New ProcessStartInfo
    pinfo.UseShellExecute = False
    pinfo.RedirectStandardOutput = True
    pinfo.Arguments = " G:\Utils\Arguments.vbs testing ""testing"" ""1 2 3"""
    pinfo.FileName = strExe
    pinfo.WorkingDirectory = "G:\Utils"
    pinfo.WindowStyle = ProcessWindowStyle.Normal
    pinfo.CreateNoWindow = True
    p.StartInfo = pinfo
    p.Start()
    

    So wscript is seeing the quotes and is accumulating three arguments for the script.

    BTW I just noticed your example attempts at getting quotes around the filename modify the fn variable. Did you cater for this with the .WorkingDirectory line, which should be using the unmodified filename?

提交回复
热议问题