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)
Samples
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:
- Encoding.GetBytes (MSDN)
- Encoding.GetString Method (MSDN)
- Encoding.Convert Method (MSDN)
- The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) (Joel on Software)
- Character encoding (WIKIPEDIA)