Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding Persian string using C#

Tags:

c#

sms

farsi

I am developing an SMS application using C# for the bank which sends transaction alerts i.e. ATM transactions to the customer through the SMS gateway. The application is working fine, the only issue is encoding the Persian text, it doesn't encode the Persian text correctly.

Here is the method which encodes Persian text to UTF-16 format.

public static string Endian2UTF(string s)        
{

     Encoding ui = Encoding.BigEndianUnicode;              
     Encoding u8 = Encoding.UTF8;              
     string str = u8.GetString(ui.GetBytes(s));              
     return str;          
}

Some characters are not getting encoded correctly, the message on mobile device looks like as below

مشترۯ뾽 ۯ뾽رامۯ뾽 شما به مقدار 500.00 افغانۯ뾽 از حساب خوب از ماشۯ뾽ن صرافۯ뾽 نماۯ뾽ندۯ뾽ۯ뾽 شهر نو بدست اوردۯ뾽د، تشۯ뾽ر از شما.

The issue is only with some characters as you see above. For your information, there is no issue with the English string.

like image 718
Hizbullah Watandost Avatar asked Oct 25 '25 00:10

Hizbullah Watandost


1 Answers

Finally, I found the issue. In the library somewhere the text was encoded incorrectly, so I traced it using debugger break point and found the root case. It was encoding the message to UTF8, once I changed it to BigEndianUnicode. It worked like a charm. Here is the code. You need to apply below changes in SendSms method in SMPPClient.cs file.

if (dataCoding == 8)
{
   //data = Encoding.UTF8.GetBytes(text);
     data = Encoding.BigEndianUnicode.GetBytes(text);
}
else
{
    data = Encoding.ASCII.GetBytes(text);
}

One more changes you need to apply if still the SMS is sent as garbage. comment the part which encode the text to UTF in SMMPClient.cs

if (dataCoding == 8)
{
    //text = Tools.Endian2UTF(text);
      maxLength = 70;
}

I hope this could help anyone who use EasySMPP library to send SMS to client.

like image 166
Hizbullah Watandost Avatar answered Oct 27 '25 14:10

Hizbullah Watandost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!