Encoding.GetPreamble Método

Definição

Quando substituído em uma classe derivada, retorna uma sequência de bytes que especifica a codificação usada.When overridden in a derived class, returns a sequence of bytes that specifies the encoding used.

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

Retornos

Byte[]

Uma matriz de bytes que contém uma sequência de bytes que especifica a codificação usada.A byte array containing a sequence of bytes that specifies the encoding used.

- ou --or-

Uma matriz de bytes de tamanho zero, se um preâmbulo não for necessário.A byte array of length zero, if a preamble is not required.

Exemplos

O exemplo a seguir determina a ordem de bytes da codificação com base no preâmbulo.The following example determines the byte order of the encoding based on the preamble.

using namespace System;
using namespace System::Text;
int main()
{
   Encoding^ unicode = Encoding::Unicode;
   
   // Get the preamble for the Unicode encoder. 
   // In this case the preamblecontains the Byte order mark (BOM).
   array<Byte>^preamble = unicode->GetPreamble();
   
   // Make sure a preamble was returned 
   // and is large enough to containa BOM.
   if ( preamble->Length >= 2 )
   {
      
      // if (preamble->Item[0] == 0xFE && preamble->Item[1] == 0xFF) 
      if ( preamble[ 0 ] == 0xFE && preamble[ 1 ] == 0xFF )
      {
         Console::WriteLine( "The Unicode encoder is encoding in big-endian order." );
      }
      // else if (preamble->Item[0] == 0xFF && preamble->Item[1] == 0xFE) 
      else
      
      // else if (preamble->Item[0] == 0xFF && preamble->Item[1] == 0xFE) 
      if ( preamble[ 0 ] == 0xFF && preamble[ 1 ] == 0xFE )
      {
         Console::WriteLine( "The Unicode encoder is encoding in little-endian order." );
      }
   }
}

/*
This code produces the following output.

The Unicode encoder is encoding in little-endian order.

*/
using System;
using System.Text;

namespace GetPreambleExample
{
   class GetPreambleExampleClass
   {
      static void Main()
      {
         Encoding unicode = Encoding.Unicode;

         // Get the preamble for the Unicode encoder. 
         // In this case the preamble contains the byte order mark (BOM).
         byte[] preamble = unicode.GetPreamble();

         // Make sure a preamble was returned 
         // and is large enough to containa BOM.
         if(preamble.Length >= 2)
         {
            if(preamble[0] == 0xFE && preamble[1] == 0xFF)
            {
               Console.WriteLine("The Unicode encoder is encoding in big-endian order.");
            }
            else if(preamble[0] == 0xFF && preamble[1] == 0xFE)
            {
               Console.WriteLine("The Unicode encoder is encoding in little-endian order.");
            }
         }
      }
   }
}

/*
This code produces the following output.

The Unicode encoder is encoding in little-endian order.

*/
Imports System.Text

Namespace GetPreambleExample
   Class GetPreambleExampleClass
      Shared Sub Main()
         Dim [unicode] As Encoding = Encoding.Unicode

         ' Get the preamble for the Unicode encoder. 
         ' In this case the preamble contains the byte order mark (BOM).
         Dim preamble As Byte() = [unicode].GetPreamble()

         ' Make sure a preamble was returned 
         ' and is large enough to contain a BOM.
         If preamble.Length >= 2 Then
            If preamble(0) = &HFE And preamble(1) = &HFF Then
               Console.WriteLine("The Unicode encoder is encoding in big-endian order.")
            Else
               If preamble(0) = &HFF And preamble(1) = &HFE Then
                  Console.WriteLine("The Unicode encoder is encoding in little-endian order.")
               End If
            End If
         End If
      End Sub
   End Class
End Namespace

'This code produces the following output.
'
'The Unicode encoder is encoding in little-endian order.
'

Comentários

Opcionalmente, o Encoding objeto fornece um preâmbulo que é uma matriz de bytes que pode ser prefixada para a sequência de bytes resultante do processo de codificação.Optionally, the Encoding object provides a preamble that is an array of bytes that can be prefixed to the sequence of bytes resulting from the encoding process. Se o preâmbulo contiver uma marca de ordem de byte (em Unicode, ponto de código U + FEFF), ele ajudará o decodificador a determinar a ordem de bytes e o formato de transformação ou UTF.If the preamble contains a byte order mark (in Unicode, code point U+FEFF), it helps the decoder determine the byte order and the transformation format or UTF.

A BOM (marca de ordem de byte) Unicode é serializada da seguinte maneira (em hexadecimal):The Unicode byte order mark (BOM) is serialized as follows (in hexadecimal):

  • UTF-8: EF BB BFUTF-8: EF BB BF

  • Ordem de byte UTF-16 big endian: FEUTF-16 big endian byte order: FE FF

  • Ordem de byte UTF-16 little endian: FF FEUTF-16 little endian byte order: FF FE

  • UTF-32 big endian ordem de bytes: 00 00 FE FFUTF-32 big endian byte order: 00 00 FE FF

  • UTF-32 little endian ordem de byte: FF FE 00 00UTF-32 little endian byte order: FF FE 00 00

Você deve usar a BOM, pois ela fornece quase certa identificação de uma codificação para arquivos que, de outra forma, perderam a referência ao Encoding objeto, por exemplo, dados da Web não marcados ou marcados incorretamente ou arquivos de texto aleatórios armazenados quando um negócio não tinha preocupações internacionais ou outros dados.You should use the BOM, because it provides nearly certain identification of an encoding for files that otherwise have lost reference to the Encoding object, for example, untagged or improperly tagged web data or random text files stored when a business did not have international concerns or other data. Geralmente, problemas de usuário podem ser evitados se os dados forem marcados de forma consistente e correta, preferencialmente em UTF-8 ou UTF-16.Often user problems might be avoided if data is consistently and properly tagged, preferably in UTF-8 or UTF-16.

Para padrões que fornecem um tipo de codificação, uma BOM é um pouco redundante.For standards that provide an encoding type, a BOM is somewhat redundant. No entanto, ele pode ser usado para ajudar um servidor a enviar o cabeçalho de codificação correto.However, it can be used to help a server send the correct encoding header. Como alternativa, ele pode ser usado como um fallback, caso a codificação seja perdida.Alternatively, it can be used as a fallback in case the encoding is otherwise lost.

Há algumas desvantagens em usar uma BOM.There are some disadvantages to using a BOM. Por exemplo, saber como limitar os campos de banco de dados que usam uma BOM pode ser difícil.For example, knowing how to limit the database fields that use a BOM can be difficult. A concatenação de arquivos também pode ser um problema, por exemplo, quando os arquivos são mesclados de forma que um caractere desnecessário possa terminar no meio dos dados.Concatenation of files can be a problem also, for example, when files are merged in such a way that an unnecessary character can end up in the middle of data. No entanto, apesar das poucas desvantagens, o uso de uma BOM é altamente recomendável.In spite of the few disadvantages, however, the use of a BOM is highly recommended.

Para obter mais informações sobre a ordem de bytes e a marca de ordem de byte, consulte o padrão Unicode na Home Page Unicode.For more information on byte order and the byte order mark, see The Unicode Standard at the Unicode home page.

Cuidado

Para garantir que os bytes codificados sejam decodificados corretamente, você deve prefixar bytes codificados com um preâmbulo.To ensure that the encoded bytes are decoded properly, you should prefix encoded bytes with a preamble. No entanto, a maioria das codificações não fornece um preâmbulo.However, most encodings do not provide a preamble. Para garantir que os bytes codificados sejam decodificados corretamente, você deve usar uma codificação Unicode, ou seja,, UTF8Encoding UnicodeEncoding ou UTF32Encoding , com um preâmbulo.To ensure that the encoded bytes are decoded properly, you should use a Unicode encoding, that is, UTF8Encoding, UnicodeEncoding, or UTF32Encoding, with a preamble.

Aplica-se a