UTF8 Encoding with C# .NET

Occasionally when working with the web you may need to UTF8 encode something you are working on. Here’s a little snippet that shows how to UTF8 encode in C#.

String script = "A string that I need to UTF8 Encode!";
if(script == null || script.Length == 0)
return "";
System.Text.UTF8Encoding newUTF8Encoding = new System.Text.UTF8Encoding();
System.Text.Encoder newEncoder = newUTF8Encoding.GetEncoder();
Int32 encodingLength =
newEncoder.GetByteCount(script.ToCharArray(), 0, script.Length, true);
Byte[] encodedScript = new Byte[ encodingLength ];
newEncoder.GetBytes(script.ToCharArray(), 0, script.Length, encodedScript, 0, true);
String uft8Script = "";
foreach(Byte b in encodedScript)
{
uft8Script += "&#"+(Int32)b+";";
}

Leave a Reply