.netvb.net

Subprocess redirected output is garbage


I have an old .NET Framework 4.8 forms app and I am trying to add the ability to run the console version of VoidTools' excellent Everything, es.exe, in a subprocess but it is not working. The output is a bunch of chinese characters. The command parameter is the full path (which contains spaces) and filename of the exe and I've tried with and without double quotes. The command and parameters work fine in a normal command prompt.

Here is the code. Any ideas why?

Function ExecuteCommand(command As String, args As String) As String
    Dim processStartInfo As New ProcessStartInfo()
    processStartInfo.FileName = command
    processStartInfo.Arguments = args
    'processStartInfo.FileName = "cmd.exe"
    'processStartInfo.Arguments = " /c " & dblquoted(command) & " " & args
    processStartInfo.RedirectStandardOutput = True
    processStartInfo.RedirectStandardError = True
    processStartInfo.UseShellExecute = False ' This prevents a window from appearing
    processStartInfo.CreateNoWindow = True ' No window

    Dim process As New Process()
    process.StartInfo = processStartInfo

    Dim output As String
    Dim errorOutput As String

    Try
        process.Start()
        output = process.StandardOutput.ReadToEnd()
        errorOutput = process.StandardError.ReadToEnd()
        process.WaitForExit()
    Catch ex As Exception
        Return $"An error occurred: {ex.Message}"
    End Try

    ' Combine stdout and stderr for completeness
    Return output & Environment.NewLine & errorOutput
End Function

Solution

  • Nice title .3.

    Probably encoding issue, setting Encoding to UTF8 will probably solve the issue.

    Try This:

    processStartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8
    processStartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8