Returns string build up with bytes - no encoding is used. PROS: No data loss as with encoding when char is illegal. - CSharp System

CSharp examples for System:Char

Description

Returns string build up with bytes - no encoding is used. PROS: No data loss as with encoding when char is illegal.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Linq;
using System.IO;/*from w  w w  . j  av  a 2s . c o m*/
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
      /// Returns string build up with bytes - no encoding is used.
      /// PROS: No data loss as with encoding when char is illegal.
      /// CONS: This and ToString method must be both used on same machine - Other case not tested.
      /// Source: http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp
      /// </summary>
      /// <param name="bytes"></param>
      /// <returns></returns>
      public static string ToString(this byte[] bytes)
      {
         char[] chars = new char[bytes.Length / sizeof(char)];
         System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
         return new string(chars);
      }
}

Related Tutorials