I'm working on a C# app that needs to convert UTF16 text to UTF8, and WideCharToMultiByte (an unmanaged API in kernel32.dll) does it quite nicely.
Problem is - it's the only unmanaged piece of code in my solution, and I'd give my kingdom (as small as it may be) for advice on how to implement it in C# and therefore remove the dependency on non-dotnet resources.
I've done quite a bit of searching and playing around, and have tried quite a few things with the encoder classes. Nothing gets there.
Here's the encoder code that got the closest:
The output of this is that destString = "bet??n".
If, however, I try to convert the string with a call to old-faithful as follows:
The output of this is that destStringBuilder = "betún", which is the correct result.
Any ideas?
Problem is - it's the only unmanaged piece of code in my solution, and I'd give my kingdom (as small as it may be) for advice on how to implement it in C# and therefore remove the dependency on non-dotnet resources.
I've done quite a bit of searching and playing around, and have tried quite a few things with the encoder classes. Nothing gets there.
Here's the encoder code that got the closest:
Code:
string sourceString = "betún";
string destString = "";
System.Text.UTF8Encoding utf8Encoding = new System.Text.UTF8Encoding();
byte[] encodedBytes = utf8Encoding.GetBytes(sourceString);
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
destString = asciiEncoding.GetString(encodedBytes);
The output of this is that destString = "bet??n".
If, however, I try to convert the string with a call to old-faithful as follows:
Code:
string sourceString = "betún";
StringBuilder destStringBuilder = new StringBuilder(myString.Length * 3 + 1);
int result = WideCharToMultiByte(
65001, //Use the code page used in your unmanaged code
0, // Flags could be 0 in most cases see SDK doc.
sourceString, // string to convert
sourceString.Length,
destStringBuilder,
destStringBuilder.Capacity,
IntPtr.Zero,
IntPtr.Zero);
The output of this is that destStringBuilder = "betún", which is the correct result.
Any ideas?