Encoding question

Hello

I have an encoding problem.
On a Desktop Application (Full Framework) I am reading data from a File using FileStream.
I am reading 10'000 Bytes with fileStream.Read(.....)
Then I am converting it using Encoding.UTF8.GetString to a string.
Then I am adding some value to it and using Encoding.UTF8.GetBytes I am converting it back to a ByteArray which I then send to Silverlight.

There I am reading Bytes from a Stream, but when I then convert it back to UTF8-String, I get something other than what I had before.

Only if I convert it to Base64 on both sides, it is working.

Is it because some File Data cannot be stored in UTF8?

Thanks

James
RuttensoftAsked:
Who is Participating?
 
Meir RivkinFull stack Software EngineerCommented:
generaly yes.
To convert a simple UTF-8 coded text into a Base64 string in C# you can use this:
string result = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(utf8Text));

The ToBase64String method gets a byte array as a parameter and gives the encoded string back. The result can be stored in a simple string, because the base64 string is a readable ASCII string.

Decoding
To decode a UTF-8 text is a slightly more difficult than the encoding.

byte[] toDecodeByte = Convert.FromBase64String(textToTransform);

System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();

int charCount = utf8Decode.GetCharCount(toDecodeByte, 0, toDecodeByte.Length);

char[] decodedChar = new char[charCount];
utf8Decode.GetChars(toDecodeByte, 0, toDecodeByte.Length, decodedChar, 0);
string result = new String(decodedChar);

The decoding - like before - can be done with calling a method from the Convert class. The only problem with this, that is gives back a byte array as a result. It should be converted to a UTF-8 string with the System.Text namespace's Decoder class.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.