问题
I'm using windows 10 (maybe this is the problem:-) )
I have a simple code that reads text in Hebrew from console them print it's HEX\DEC value
but he give me 00 all the time on the console window I can see the Hebrew letters
any reason why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.IO;
namespace HebTest
{
class Program
{
static public void Main(string[] args)
{
Console.WriteLine("Write your message here - ");
string StringMessage = Console.ReadLine();
Console.WriteLine("print string - " + StringMessage);
///message in HEX
byte [] ByteMessage = Encoding.Default.GetBytes(StringMessage);
string HexMessage = BitConverter.ToString(ByteMessage);
Console.WriteLine("MSG in HEX - " + HexMessage);
Console.Write(
Encoding.Default.GetString(ByteMessage)
);
Console.WriteLine();
foreach (byte p in ByteMessage)
{
Console.Write((char)p + " - " + p );
Console.WriteLine("");
}
}
for example I enter this text "test אבגד" and this is what I got :
Write your message here -
test אבגד ---> this I wrote on the console
print string - test
MSG in HEX - 74-65-73-74-20-00-00-00-00
test
t - 116
e - 101
s - 115
t - 116
- 32
- 0
- 0
- 0
- 0
what am I missing?
Thanks ,
回答1:
You're using Encoding.Default
to convert the string into binary. That's almost always a bad idea - it means the same code may work on some machines and not on others. It's pretty much only useful when you want to read/write a text file on that machine, and you're sure that the system default encoding is the right one to use for any machine that runs it. That's rare.
In particular, you're trying to talk to an external device - which means you need to use the encoding it expects. You should find that out, and use the appropriate encoding. For example, if the device expects UTF-8, use:
// Local variable names changed to be more idiomatic C#
string text = Console.ReadLine();
byte[] bytes = Encoding.UTF8.GetBytes(text);
As you've now indicated that the device expects Windows-1255, that's code page 1255, so you get the encoding like this:
Encoding.GetEncoding(1255)
For clarify, I'd probably use a separate variable for that:
string text = Console.ReadLine();
Encoding encoding = Encoding.GetEncoding(1255);
byte[] bytes = encoding.GetBytes(text);
回答2:
Found the problem (after @Daisy Shipton let me think )
the code is OK need to go to control Panel - region - administrative - system locale -
REMOVE V on Beta : use Unicode UTF-8 for worldwide language support
hope it will help someone someday
来源:https://stackoverflow.com/questions/51653551/c-sharp-reading-hebrew-text-from-console