0

I have a function that gets data from buffer and converts them to string as you can see :

public string GetParameters(byte[] buf)
{
    string result = System.Text.UnicodeEncoding.Unicode.GetString(buf);
    return result;
}

Another application sends a Farsi string to buffer and my application should get this data, but my application's function returns this:

㨲께裙듘�����¯

Why ? enter image description here

How can i receive buffer data : I define this :

public byte[] dataBuffer = new byte[4000];

I have this function :

 public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    // Specify the call back function which is to be 
                    // invoked when there is any write activity by the 
                    // connected client
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.m_currentSocket = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc.BeginReceive(theSocPkt.dataBuffer, 0,
                                   theSocPkt.dataBuffer.Length,
                                   SocketFlags.None,
                                   pfnWorkerCallBack,
                                   theSocPkt);
            }
            catch (Exception qqq)
            {

            }

        }

And another one :

 public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                string res = GetParameters(socketData.dataBuffer);
}
Ehsan Akbar
  • 6,977
  • 19
  • 96
  • 180

2 Answers2

2

Try to use UTF-8:

string result = System.Text.UnicodeEncoding.UTF8.GetString(buf);

That looks like Farsi to me. (But I don't speak Farsi.)

The differences between Unicode and UTF-8 are mentioned here: UTF-8 vs. Unicode

Essentially the length of a character makes the difference.

Community
  • 1
  • 1
haindl
  • 3,111
  • 2
  • 25
  • 31
-2

string myDecodedString = Encoding.GetEncoding("1256").GetString(buf)

raidensan
  • 1,099
  • 13
  • 31
  • {"'1256' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.\r\nParameter name: name"} – Ehsan Akbar Oct 12 '16 at 09:11