Tuesday, August 30, 2005

Convert from byte[] to string in C#.NET

Recently I had to convert a byte[] array to a string in .NET. I knew that there should be some method somewhere which takes a encoding and returns the string accordingly.
I searched in the "byte[]" class, then in the "string" class, but could not find any appropriate method. Finally I found it in the System.Text.Encoding class. It has other subclasses such as
System.Text.ASCIIEncoding,
System.Text.UnicodeEncoding,
System.Text.UTF7Encoding,
System.Text.UTF8Encoding.

Code snippet:

System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(myByteArray );

I would have preferred a String Constructor which takes a byte[] and a encoding string. Much more intuitive...

No comments:

Post a Comment