Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CMD/console encoding in C#

Tags:

c#

cmd

console

I need to specify the correct codepage to pack the files with zip library. As I see, I need to specify console encoding (866 in my case).

 C:\Users\User>mode

 Status for device CON:
 ----------------------
     Lines:          300
     Columns:        130
     Keyboard rate:  31
     Keyboard delay: 1
     Code page:      866 <- I need to get this value in C# code

Console.OutputEncoding returns 1251, which is not what I need.

Thanks,

Alex

Update 1: Obviously, execute "mode" in cmd.exe and parse output should work but it seems too rude. I'm looking for .NET solution.

Update 2: The application is windows forms application, not a console app.

like image 889
Alex Netkachov Avatar asked May 06 '11 11:05

Alex Netkachov


People also ask

What is chcp command?

Changes the active console code page. If used without parameters, chcp displays the number of the active console code page.


2 Answers

for me 852 (Latin II):

Encoding consoleEncoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
like image 194
tibx Avatar answered Oct 04 '22 11:10

tibx


The default code page for a console mode app is determined by the system locale. Control Panel + Region and Language, Administrative tab, Change System Locale. Your Windows code page is Cyrillic, so is your console code page so there's a reasonable chance that this code will work:

        int lcid = GetSystemDefaultLCID();
        var ci = System.Globalization.CultureInfo.GetCultureInfo(lcid);
        var page = ci.TextInfo.OEMCodePage;
        // etc..

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    public static extern int GetSystemDefaultLCID();

Do avoid writing code like this, 8-bit text encodings are a mine field. There certainly isn't any decent reason to have to run a console-mode zip program, there are plenty of .NET zip libraries available.

like image 29
Hans Passant Avatar answered Oct 04 '22 13:10

Hans Passant