Converts string to an array of bytes, using specified Encoding. - CSharp System

CSharp examples for System:Byte

Description

Converts string to an array of bytes, using specified Encoding.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;/*w  ww . j a v a  2 s.  co m*/

public class Main{
        /// <summary>
    ///   <para>Converts string to an array of bytes, using specified <see cref="Encoding"/>.</para>
    /// </summary>
    /// <param name="self">String that consists of characters that are to be transformed to bytes.</param>
    /// <param name="encoding">Encoding to be used for transformation between characters of <paramref name="self"/> and their bytes equivalents. If not specified, default <see cref="Encoding.UTF8"/> is used.</param>
    /// <param name="preamble">Whether to append byte preamble of <paramref name="encoding"/> to the beginning of the resulting byte array.</param>
    /// <returns>Array of bytes that form <paramref name="self"/> string in given <paramref name="encoding"/>.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="self"/> is a <c>null</c> reference.</exception>
    /// <seealso cref="Encoding.GetBytes(string)"/>
    public static byte[] Bytes(this string self, Encoding encoding = null, bool preamble = true)
    {
      Assertion.NotNull(self);

      var textEncoding = encoding ?? Encoding.UTF8;
      return preamble ? textEncoding.GetPreamble().Join(textEncoding.GetBytes(self)) : textEncoding.GetBytes(self);
    }
}

Related Tutorials