To change the encoding of a String using .NET you can use this Extension Method which is part of the Fesslersoft.Extensions. This method needs a source and a target encoding. Some people might find the source encoding parameter needless, but as Joel stated in his excellent blogpost

“It does not make sense to have a string without knowing what encoding it uses” (Joel Spolsky)


Sample C#

public static string ChangeEncoding(this string input, Encoding sourceEncoding, Encoding targetEncoding)
	byte[] utfBytes = sourceEncoding.GetBytes(input);
	byte[] isoBytes = Encoding.Convert(sourceEncoding, targetEncoding, utfBytes);
	return targetEncoding.GetString(isoBytes);

VB.NET Sample

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ChangeEncoding(input As String, sourceEncoding As Encoding, targetEncoding As Encoding) As String
	Dim utfBytes As Byte() = sourceEncoding.GetBytes(input)
	Dim isoBytes As Byte() = Encoding.Convert(sourceEncoding, targetEncoding, utfBytes)
	Return targetEncoding.GetString(isoBytes)
End Function

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Leave a Reply