How to convert UTF7 string into ANSI in C#

The simplest way to transforming a UTF-7 encoded string is to use the .net System.Text.Encoding abstract class. It internally uses System.Security class library to provide the transform we are targeting for like ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, and UTF8.

decoding UTF7 string to ANSI ASCII in C#

The simplest use for transforming can be as:


protected string DecodeFromUtf7(string utf7String) { byte[] bytes = Encoding.Default.GetBytes(utf7String); return Encoding.UTF7.GetString(bytes); }

You can also create a library class where you may place encoding/decoding methods, like below sample-


using System.Text; namespace CodePattern.EncodingDecodingSample.Core { public class Utility { public static string DecodeFromUtf7(string utf7String) { byte[] bytes = Encoding.Default.GetBytes(utf7String); return Encoding.UTF7.GetString(bytes); } public static string DecodeFromUtf8(string utf8String) { byte[] bytes = Encoding.Default.GetBytes(utf8String); return Encoding.UTF8.GetString(bytes); } public static string DecodeFromUtf32(string utf32String) { byte[] bytes = Encoding.Default.GetBytes(utf32String); return Encoding.UTF32.GetString(bytes); } public static string DecodeFromBigEndianUnicode(string bigEndianUnicodeString) { byte[] bytes = Encoding.Default.GetBytes(bigEndianUnicodeString); return Encoding.BigEndianUnicode.GetString(bytes); } public static string DecodeFromUnicode(string unicodeString) { byte[] bytes = Encoding.Default.GetBytes(unicodeString); return Encoding.Unicode.GetString(bytes); } } }

And then you can use it like-


using Microsoft.VisualStudio.TestTools.UnitTesting; using CodePattern.EncodingDecodingSample.Core; namespace CodePattern.EncodingDecodingSample.Tests { [TestClass()] public class CountryRepositoryTests { [TestMethod()] public void FindByCountryNameTest() { string myUtf7EncodedString = "C:+AFw-00+AF8-KTM+AF8-thin+AF8-dialog+AFw-00+AF8-KTM+AF8-thin+AF8-dialog.fpr"; string decodedString = Utility.DecodeFromUtf7(myUtf7EncodedString); Assert.AreEqual(@"C:\00_KTM_thin_dialog\00_KTM_thin_dialog.fpr", decodedString); } } }

If you love extension methods, you can also write it too, like-


using System.Text; namespace CodePattern.EncodingDecodingSample.Extensions { public static string DecodeAsNormalString(this string unicodeString) { byte[] bytes = Encoding.Default.GetBytes(unicodeString); return Encoding.Unicode.GetString(bytes); } }

And simply use this extension method like-


string decodedString = myUtf7EncodedString.DecodeAsNormalString();


Thats it!


@AnilAwadh

blog comments powered by Disqus