Export (0) Print
Expand All

UTF8Encoding Constructor (Boolean)

Initializes a new instance of the UTF8Encoding class. A parameter specifies whether to provide a Unicode byte order mark.

Namespace:  System.Text
Assemblies:   System.Text.Encoding.Extensions (in System.Text.Encoding.Extensions.dll)
  mscorlib (in mscorlib.dll)

public UTF8Encoding(
	bool encoderShouldEmitUTF8Identifier
)

Parameters

encoderShouldEmitUTF8Identifier
Type: System.Boolean

true to specify that the GetPreamble method returns a Unicode byte order mark; otherwise, false. See the Remarks section for more information.

This constructor creates an instance that does not throw an exception when an invalid encoding is detected.

NoteNote

For security reasons, you should enable error detection by calling a constructor that includes a throwOnInvalidBytes parameter and setting its value to true.

The encoderShouldEmitUTF8Identifier parameter controls the operation of the GetPreamble method. If true, the method returns a byte array containing the Unicode byte order mark (BOM) in UTF-8 format. If false, it returns a zero-length byte array. However, setting encoderShouldEmitUTF8Identifier to true does not cause the GetBytes method to prefix the BOM at the beginning of the byte array, nor does it cause the GetByteCount method to include the number of bytes in the BOM in the byte count.

The following example creates a new UTF8Encoding instance and specifies that a Unicode byte order mark prefix should be emitted by the GetPreamble method. The GetPreamble method then returns the Unicode byte order mark prefix.

using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        UTF8Encoding utf8 = new UTF8Encoding();
        UTF8Encoding utf8EmitBOM = new UTF8Encoding(true);

        Console.WriteLine("utf8 preamble:");
        ShowArray(utf8.GetPreamble());

        Console.WriteLine("utf8EmitBOM:");
        ShowArray(utf8EmitBOM.GetPreamble());
    }

    public static void ShowArray(Array theArray) {
        foreach (Object o in theArray) {
            Console.Write("[{0}]", o);
        }
        Console.WriteLine();
    }
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft