Encoding issue when capturing console application output in a test
Asked Answered
H

2

6

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?

Handtohand answered 27/1, 2012 at 23:49 Comment(1)
how are you running your console app from your test runner?Ashmead
A
5

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");
Ashmead answered 28/1, 2012 at 0:26 Comment(2)
I've come across this issue. I'm redirecting output to a file and running from a cmd prompt but I would like output to remain encoded in UTF-8. Is there a way to set this in a command window? as I'm not starting the process via another C# application. ThanksBlondell
@ChrisWalsh see #388990 ? chcp 65001Ashmead
P
1

I think you are on the right track. As a test I executed this code:

Console.WriteLine(Encoding.Default.EncodingName);           
Console.WriteLine(Console.Out.Encoding.EncodingName);   

When run as a console application it outputs:

Western European (Windows)
OEM United States

When run as a windows application it outputs:

Western European (Windows)
Western European (Windows)

I suspect that when reading from the console output from the test runner you will need to set the encoding of your reader to match the encoding that the output is written in, probably Western European (Windows), though I can't know for sure.

Passel answered 28/1, 2012 at 0:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.