Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding issue when capturing console application output in a test

I'm trying to capture output from a console application by running it in a test using System.Diagnostics.Process. I'm having trouble with character encoding. "£" is showing up as "œ" in the test, but when I run the console application it displays correctly as "£".

If I set Console.Out.Encoding = Encoding.Default, it works in the tests but doesn't display properly when running normally.

What's going on here and how do I fix it?

like image 846
JontyMC Avatar asked Jan 27 '12 23:01

JontyMC


People also ask

How can I see the output of a console application in Visual Studio?

Press F11 . Visual Studio calls the Console. WriteLine(String, Object, Object) method. The console window displays the formatted string.

Where is the output of console WriteLine?

In Visual Studio uppermost menu choose Debug > Windows > Output. It shows all Console. WriteLine("Debug MyVariable: " + MyVariable) when you get to them. Set breakpoint before, debug, and then use F11 to step through code line by line.

How do I keep the console window open in C#?

The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5. The console window will remain open when the program has finished.

What is console application in C sharp?

A console application, in the context of C#, is an application that takes input and displays output at a command line console with access to three basic data streams: standard input, standard output and standard error.


1 Answers

You need to set the StandardOutputEncoding on your ProcessStartInfo object in your test case:

var process = new Process();
var startInfo = new ProcessStartInfo(@"yourapp.exe");
startInfo.StandardOutputEncoding = Encoding.GetEncoding(850);

You can find what CodePage you are using in your console app by running

Console.WriteLine(Console.Out.Encoding.CodePage); 

which returns 850 (Western European DOS)

You could also use the BodyName property as an arg to GetEncoding that is:

startInfo.StandardOutputEncoding = Encoding.GetEncoding("ibm850");
like image 175
wal Avatar answered Sep 28 '22 06:09

wal