Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting ConsoleOutput containing pseudo-loc (unicode) strings in C#

I'm running a console app (myApp.exe) which outputs a pseudo localized (unicode) string to the standard output. If I run this in a regular command prompt(cmd.exe), the unicode data gets lost. If I run this in a unicode command prompt(cmd.exe /u) or set the properties of the console to "Lucida Console" then the unicode string is maintained.

I'd like to run this app in C# and redirect the unicode string into a local variable. I'm using a Process object with RedirectStandardOutput = true, but the unicode string is always lost.

How can I specify to persist this unicode info?

        private static int RunDISM(string Args, out string ConsoleOutput)
        {
            Process process = new Process();
            process.StartInfo.FileName = "myApp.exe";
            process.StartInfo.Arguments = Args;

            try
            {
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;

                process.Start();
                process.WaitForExit(Int32.MaxValue);
            }
            catch (Exception e)
            {
                WEX.Logging.Interop.Log.Assert("Failure while starting or running process.\nERROR: " + e.Message);
                ConsoleOutput = null;
                return EXITCODE_ERROR;
            }

            ConsoleOutput = process.StandardOutput.ReadToEnd();
            return process.ExitCode;
        } 
like image 232
Kenn Avatar asked Oct 15 '08 23:10

Kenn


2 Answers

It looks like you need to change the encoding on the StandardOutput stream from your console app, using the StandardOutputEncoding property on ProcessStartInfo. Try adding the following code inside your try/catch block, before starting the process:

process.StartInfo.StandardOutputEncoding = Encoding.Unicode;

You might have to experiment with different encodings to see which is the right one for your case.

like image 99
Charlie Avatar answered Nov 04 '22 01:11

Charlie


Get the bytes out and see if they make any sense:

var b = p.StandardOutput.CurrentEncoding.GetBytes(p.StandardOutput.ReadToEnd());

Once you figured out the actual encoding you can use the standard encoding APIs to convert the bytes into a string.

like image 45
ziya Avatar answered Nov 04 '22 01:11

ziya