How to convert a string to ASCII in c#

This is one of those cases where smart-ass developers will tell you that you should not be converting strings to ASCII, because reasons

However, if you’re sending a file to a host-to-host banking system, or sending text to an external web service that then sends SMS messages, you might find yourself in a situation where your request will be rejected. Now while it might be frowned upon to blindly try converting Unicode to ASCII, I prefer, when submitting millions (or maybe thousands) of debit orders to a bank, that the whole fucking batch doesn’t get rejected because of some stupid character that the bank doesn’t understand.

Anyway, I can’t remember where I found this code, but the key is to use String.Normalize, to normalize a string using full compatibility decomposition – which generally results in a conversion that looks about as correct as you’re going to get by manually fixing a badly input string… and then throw away all characters that are outside of the ASCII range.

This works:

using System.Linq;
using System.Text;

namespace Demo
{
    class Example
    {
        public static string LatinToAscii(string s)
        {
            var builder = new StringBuilder();
            builder.Append(s.Normalize(NormalizationForm.FormKD)
                                            .Where(x => x < 128)
                                            .ToArray());
            return builder.ToString();
        }
    }
}
Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in General, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s