April 21, 2005

Convert from byte[] to string

Do you have this compilering error message?
"Argument '?': cannot convert from 'byte[]' to 'string' ???.cs" with .Net Compiler .Net 1.0 or .Net 2..0?
Do you have any problem for converting between 'byte[]' to 'string' (from 'byte[]' to 'string' or from 'string' to 'byte[]')?
Ok! Don’t worry.
You can use Encoding class (library).

In this example ABC is the name of a project and A01 is a resource with byte[] format.
String strTest = Encoding.ASCII.GetString(ABC.Properties.Resources.A01);
Byte[] bytTest = Encoding.ASCII.GetBytes(strTest);
So easy! Yes?
عجیبه باز یادم رفت که باید تو این دات نت همش از انکدینگ و دیکدینگ استفاده کنیم.
دوتا مثال بالا مثل روز راه رو نشون میده (یه چیزی هم روش!!!)


Amastaneh said...

this can useful for another error message like this ...
Error: Cannot convert value of parameter 'Picture' from 'System.String' to 'System.Byte[]'
I hope this helps.

Amastaneh said...

Error: Cannot convert type 'char[]' to 'string'

For converting from char array to string you can use of new string()
like below ...

char[] buffer = new char[200];
reader.ReadBlock(buffer, 0, 200);
line = new string(buffer);