.

UTF8/String coversions (byte[] / string convert)

Here follow some really usefull UTF8/String coversions below: 

They are usually used for converting streams to strings:

using System.Text;

 

private String UTF8ByteArrayToString(Byte[] characters)
{  
    UTF8Encoding encoding = new UTF8Encoding(); 
    String constructedString = encoding.GetString(characters); 
    return (constructedString);
} 
           

private Byte[] StringToUTF8ByteArray(String pXmlString)
{    
    UTF8Encoding encoding = new UTF8Encoding();    
    Byte[] byteArray = encoding.GetBytes(pXmlString);    
    return byteArray;
}

 

		

//Stream to String
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
    string content = sr.ReadToEnd();
    SaveInDB(ms);
}

//String to Stream
string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray); 
byte[] outBuf = ms.GetBuffer(); //error here



using(MemoryStream stream = new MemoryStream())
    {
        stream.Position = 0;
        var sr = new StreamReader(stream);
        string myStr = sr.ReadToEnd();
    }

What's your thoughts on this?

*

Protected by WP Anti Spam