UTF8Encoding.GetPreamble 메서드

정의

UTF8Encoding 인코딩 개체가 제공하도록 구성된 경우 UTF-8 형식으로 인코딩된 유니코드 바이트 순서 표시를 반환합니다.

public:
 override cli::array <System::Byte> ^ GetPreamble();
public override byte[] GetPreamble ();
override this.GetPreamble : unit -> byte[]
Public Overrides Function GetPreamble () As Byte()

반환

Byte[]

UTF8Encoding 인코딩 개체가 제공하도록 구성된 경우 유니코드 바이트 순서 표시가 포함된 바이트 배열입니다. 그렇지 않으면 이 메서드는 길이가 0인 바이트 배열을 반환합니다.

예제

다음 예제에서는 메서드를 GetPreamble 사용하여 UTF-8 형식으로 인코딩된 유니코드 바이트 순서 표시를 반환합니다. 매개 변수가 없는 생성자는 UTF8Encoding 프리앰블을 제공하지 않습니다.

using namespace System;
using namespace System::Text;
using namespace System::Collections;

void ShowArray(array<Byte>^ bytes)
{
   for each (Byte b in bytes)
      Console::Write( "{0:X2} ", b);

   Console::WriteLine();
}

int main()
{
   // The default constructor does not provide a preamble.
   UTF8Encoding^ UTF8NoPreamble = gcnew UTF8Encoding;
   UTF8Encoding^ UTF8WithPreamble = gcnew UTF8Encoding( true );
   array<Byte>^preamble;
   preamble = UTF8NoPreamble->GetPreamble();
   Console::WriteLine( "UTF8NoPreamble" );
   Console::WriteLine( " preamble length: {0}", preamble->Length );
   Console::Write( " preamble: " );
   ShowArray( preamble );
   Console::WriteLine();
   
   preamble = UTF8WithPreamble->GetPreamble();
   Console::WriteLine( "UTF8WithPreamble" );
   Console::WriteLine( " preamble length: {0}", preamble->Length );
   Console::Write( " preamble: " );
   ShowArray( preamble );
}
// The example displays the following output:
//       UTF8NoPreamble
//        preamble length: 0
//        preamble:
//
//       UTF8WithPreamble
//        preamble length: 3
//        preamble: EF BB BF
using System;
using System.Text;

class Example
{
    public static void Main()
    {
        // The default constructor does not provide a preamble.
        UTF8Encoding UTF8NoPreamble = new UTF8Encoding();
        UTF8Encoding UTF8WithPreamble = new UTF8Encoding(true);

        Byte[] preamble;

        preamble = UTF8NoPreamble.GetPreamble();
        Console.WriteLine("UTF8NoPreamble");
        Console.WriteLine(" preamble length: {0}", preamble.Length);
        Console.Write(" preamble: ");
        ShowArray(preamble);
        Console.WriteLine();
        
        preamble = UTF8WithPreamble.GetPreamble();
        Console.WriteLine("UTF8WithPreamble");
        Console.WriteLine(" preamble length: {0}", preamble.Length);
        Console.Write(" preamble: ");
        ShowArray(preamble);
    }

    public static void ShowArray(Byte[] bytes)
    {
        foreach (var b in bytes)
            Console.Write("{0:X2} ", b);

        Console.WriteLine();
    }
}
// The example displays the following output:
//    UTF8NoPreamble
//     preamble length: 0
//     preamble:
//
//    UTF8WithPreamble
//     preamble length: 3
//     preamble: EF BB BF
Imports System.Text

Module Example
    Public Sub Main()
        ' The default constructor does not provide a preamble.
        Dim UTF8NoPreamble As New UTF8Encoding()
        Dim UTF8WithPreamble As New UTF8Encoding(True)
        
        Dim preamble() As Byte
        
        preamble = UTF8NoPreamble.GetPreamble()
        Console.WriteLine("UTF8NoPreamble")
        Console.WriteLine(" preamble length: {0}", preamble.Length)
        Console.Write(" preamble: ")
        ShowArray(preamble)
        Console.WriteLine()
        
        preamble = UTF8WithPreamble.GetPreamble()
        Console.WriteLine("UTF8WithPreamble")
        Console.WriteLine(" preamble length: {0}", preamble.Length)
        Console.Write(" preamble: ")
        ShowArray(preamble)
    End Sub

    Public Sub ShowArray(bytes As Byte())
        For Each b In  bytes
            Console.Write("{0:X2} ", b)
        Next
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output:
'    UTF8NoPreamble
'     preamble length: 0
'     preamble:
'
'    UTF8WithPreamble
'     preamble length: 3
'     preamble: EF BB BF

다음 예제에서는 두 UTF8Encoding 개체를 인스턴스화합니다. 첫 번째 개체는 BOM을 제공하지 않는 매개 변수가 없는 UTF8Encoding() 생성자를 호출하고, 두 번째 개체는 인수가 설정된 생성자를 encoderShouldEmitUTF8Identifier 호출 UTF8Encoding(Boolean) 하여 인스턴스화합니다true. 그런 다음 UF8로 인코딩된 문자열을 작성하기 전에 파일에 BOM을 쓰는 메서드를 호출 GetPreamble 합니다. 예제의 콘솔 출력에서 보여 주듯이 두 번째 인코더의 바이트를 저장하는 파일에는 첫 번째 바이트보다 3바이트가 더 있습니다.

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      String s = "This is a string to write to a file using UTF-8 encoding.";

      // Write a file using the default constructor without a BOM.
      var enc = new UTF8Encoding();
      Byte[] bytes = enc.GetBytes(s);
      WriteToFile("NoPreamble.txt", enc, bytes);

      // Use BOM.
      enc = new UTF8Encoding(true);
      WriteToFile("Preamble.txt", enc, bytes);
   }

   private static void WriteToFile(String fn, Encoding enc, Byte[] bytes)
   {
      var fs = new FileStream(fn, FileMode.Create);
      Byte[] preamble = enc.GetPreamble();
      fs.Write(preamble, 0, preamble.Length);
      Console.WriteLine("Preamble has {0} bytes", preamble.Length);
      fs.Write(bytes, 0, bytes.Length);
      Console.WriteLine("Wrote {0} bytes to {1}.", fs.Length, fn);
      fs.Close();
      Console.WriteLine();
   }
}
// The example displays the following output:
//       Preamble has 0 bytes
//       Wrote 57 bytes to NoPreamble.txt.
//
//       Preamble has 3 bytes
//       Wrote 60 bytes to Preamble.txt.
Imports System.IO
Imports System.Text

Module Example
   Public Sub Main()
      Dim s As String = "This is a string to write to a file using UTF-8 encoding."
      
      ' Write a file using the default constructor without a BOM.
      Dim enc As New UTF8Encoding()
      Dim bytes() As Byte = enc.GetBytes(s)
      WriteToFile("NoPreamble.txt", enc, bytes)

      ' Use BOM.
      enc = New UTF8Encoding(True)
      WriteToFile("Preamble.txt", enc, bytes)
   End Sub

   Private Sub WriteToFile(fn As String, enc As Encoding, bytes As Byte())
      Dim fs As New FileStream(fn, FileMode.Create)
      Dim preamble() As Byte = enc.GetPreamble()
      fs.Write(preamble, 0, preamble.Length)
      Console.WriteLine("Preamble has {0} bytes", preamble.Length)
      fs.Write(bytes, 0, bytes.Length)
      Console.WriteLine("Wrote {0} bytes to {1}.", fs.Length, fn)
      fs.Close()
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'       Preamble has 0 bytes
'       Wrote 57 bytes to NoPreamble.txt.
'
'       Preamble has 3 bytes
'       Wrote 60 bytes to Preamble.txt.

콘솔 창에서 명령을 사용하여 fc 파일을 비교하거나 16진수 보기 모드가 포함된 텍스트 편집기에서 파일을 검사할 수도 있습니다. UTF-8을 지원하는 편집기에서 파일을 열면 BOM이 표시되지 않습니다.

설명

개체는 UTF8Encoding 인코딩 프로세스에서 발생하는 바이트 시퀀스에 접두사를 지정할 수 있는 바이트 배열인 프리앰블을 제공할 수 있습니다. 바이트 순서 표시(코드 포인트 U+FEFF)를 사용하여 인코딩된 바이트 시퀀스를 앞에 두면 디코더가 바이트 순서와 변환 형식 또는 UTF를 결정하는 데 도움이 됩니다. BOM(유니코드 바이트 순서 표시)은 0xEF 0xBB 0xBF 직렬화됩니다. 유니코드 표준은 UTF-8로 인코딩된 스트림에 BOM 사용을 요구하거나 권장하지 않습니다.

다음과 같은 방법으로 메서드가 UTF8Encoding GetPreamble 유효한 BOM을 반환하는 개체를 인스턴스화할 수 있습니다.

  • 속성에서 반환된 UTF8Encoding 개체를 검색합니다 Encoding.UTF8 .

  • 매개 변수를 사용하여 UTF8Encoding 생성자를 encoderShouldEmitUTF8Identifier 호출하고 해당 값을 으로 설정합니다 true.

다른 UTF8Encoding 모든 개체는 유효한 BOM이 아닌 빈 배열을 반환하도록 구성됩니다.

BOM은 인코딩에 대한 참조가 손실된 파일(예: 태그가 지정되지 않았거나 부적절하게 태그가 지정된 웹 데이터 또는 비즈니스에 국제적인 문제가 없을 때 저장된 임의 텍스트 파일)에 대한 인코딩을 거의 확실하게 식별합니다. 데이터가 일관되고 적절하게 태그가 지정된 경우 사용자 문제를 방지할 수 있는 경우가 많습니다.

인코딩 유형을 제공 하는 표준의 경우 BOM은 다소 중복 됩니다. 그러나 서버에서 올바른 인코딩 헤더를 보내는 데 사용할 수 있습니다. 또는 인코딩이 손실 되는 경우 대체 방법으로 사용할 수 있습니다.

BOM을 사용 하는 경우 몇 가지 단점이 있습니다. 예를 들어 BOM을 사용 하는 데이터베이스 필드를 제한 하는 방법을 알고 있는 것은 어려울 수 있습니다. 파일의 연결은 예를 들어 불필요 한 문자가 데이터 중간에 종료 될 수 있는 방식으로 파일을 병합 하는 경우에도 문제가 될 수 있습니다. 그러나 몇 가지 단점에도 불구 하 고 BOM을 사용 하는 것이 좋습니다.

바이트 순서 및 바이트 순서 표시에 대 한 자세한 내용은 유니코드 홈페이지에서 유니코드 표준을 참조 하세요.

중요

인코딩된 바이트가 파일 또는 스트림으로 저장될 때 제대로 디코딩되도록 하려면 인코딩된 바이트 스트림의 시작 부분에 프리앰블을 접두사로 지정할 수 있습니다. 메서드는 GetBytes 인코딩된 바이트 시퀀스에 BOM을 앞에 두지 않습니다. 적절한 바이트 스트림의 시작 부분에 BOM을 제공하는 것은 개발자의 책임입니다.

적용 대상