Share via


UTF32Encoding.GetPreamble Metodo

Definizione

Restituisce un byte order mark Unicode codificato in formato UTF-32, se l'oggetto di codifica UTF32Encoding è configurato per fornirne uno.

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

Restituisce

Byte[]

Matrice di byte contenente il byte order mark Unicode, se l'oggetto UTF32Encoding è configurato per fornirne uno. In caso contrario, questo metodo restituisce una matrice di byte di lunghezza zero.

Esempio

L'esempio di codice seguente recupera e visualizza il contrassegno dell'ordine di byte per istanze diverse UTF32Encoding .

using namespace System;
using namespace System::Text;

void PrintHexBytes( array<Byte>^bytes );

int main()
{
   
   // Create instances of UTF32Encoding, with the byte order mark and without.
   UTF32Encoding ^ u32LeNone = gcnew UTF32Encoding;
   UTF32Encoding ^ u32BeNone = gcnew UTF32Encoding( true,false );
   UTF32Encoding ^ u32LeBom = gcnew UTF32Encoding( false,true );
   UTF32Encoding ^ u32BeBom = gcnew UTF32Encoding( true,true );
   
   // Display the preamble for each instance.
   PrintHexBytes( u32LeNone->GetPreamble() );
   PrintHexBytes( u32BeNone->GetPreamble() );
   PrintHexBytes( u32LeBom->GetPreamble() );
   PrintHexBytes( u32BeBom->GetPreamble() );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This example displays the following output:
      FF FE 00 00
      <none>
      FF FE 00 00
      00 00 FE FF
*/
using System;
using System.Text;

public class SamplesUTF32Encoding
{
   public static void Main()
   {
      // Create instances of UTF32Encoding, with the byte order mark and without.
      UTF32Encoding u32LeNone = new UTF32Encoding();
      UTF32Encoding u32BeNone = new UTF32Encoding( true, false );
      UTF32Encoding u32LeBom  = new UTF32Encoding( false, true );
      UTF32Encoding u32BeBom  = new UTF32Encoding( true, true );

      // Display the preamble for each instance.
      PrintHexBytes( u32LeNone.GetPreamble() );
      PrintHexBytes( u32BeNone.GetPreamble() );
      PrintHexBytes( u32LeBom.GetPreamble() );
      PrintHexBytes( u32BeBom.GetPreamble() );
   }

   public static void PrintHexBytes( byte[] bytes )
   {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}
/*
This example displays the following output.
      FF FE 00 00
      <none>
      FF FE 00 00
      00 00 FE FF
*/
Imports System.Text

Public Class SamplesUTF32Encoding   
   Public Shared Sub Main()
      ' Create instances of UTF32Encoding, with the byte order mark and without.
      Dim u32LeNone As New UTF32Encoding()
      Dim u32BeNone As New UTF32Encoding(True, False)
      Dim u32LeBom As New UTF32Encoding(False, True)
      Dim u32BeBom As New UTF32Encoding(True, True)

      ' Display the preamble for each instance.
      PrintHexBytes(u32LeNone.GetPreamble())
      PrintHexBytes(u32BeNone.GetPreamble())
      PrintHexBytes(u32LeBom.GetPreamble())
      PrintHexBytes(u32BeBom.GetPreamble())
   End Sub

   Public Shared Sub PrintHexBytes(bytes() As Byte)
      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If
   End Sub
End Class
'This example displays the following output:
'       FF FE 00 00
'       FF FE 00 00
'       00 00 FE FF

L'esempio seguente crea un'istanza di due UTF32Encoding oggetti, il primo dei quali non fornisce un BOM e il secondo di cui esegue. Chiama quindi il metodo per scrivere il GetPreamble BOM in un file prima di scrivere una stringa con codifica UTF-32. Come illustrato dall'output dell'esempio, il file che salva i byte dal secondo codificatore ha quattro byte più byte che il primo.

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-32 encoding.";

      // Write a file using the default constructor without a BOM.
      var enc = new UTF32Encoding(! BitConverter.IsLittleEndian, false);
      Byte[] bytes = enc.GetBytes(s);
      WriteToFile(@".\NoPreamble.txt", enc, bytes);

      // Use BOM.
      enc = new UTF32Encoding(! BitConverter.IsLittleEndian, 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 232 bytes to .\NoPreamble.txt.
//
//       Preamble has 4 bytes
//       Wrote 236 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-32 encoding."
      
      ' Write a file using the default constructor without a BOM.
      Dim enc As New UTF32Encoding(Not BitConverter.IsLittleEndian, False)
      Dim bytes() As Byte = enc.GetBytes(s)
      WriteToFile("NoPreamble.txt", enc, bytes)

      ' Use BOM.
      enc = New UTF32Encoding(Not BitConverter.IsLittleEndian, 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 232 bytes to NoPreamble.txt.
'
'       Preamble has 4 bytes
'       Wrote 236 bytes to Preamble.txt.

È anche possibile confrontare i file usando il fc comando in una finestra della console oppure è possibile esaminare i file in un editor di testo che include una modalità visualizzazione hex. Si noti che quando il file viene aperto in un editor che supporta UTF-32, la BOM non viene visualizzata.

Commenti

L'oggetto UTF32Encoding può fornire un preambolo, ovvero una matrice di byte che può essere preceduta dalla sequenza di byte risultanti dal processo di codifica. Prefacing di una sequenza di byte codificati con un contrassegno di ordine di byte (punti di codice U+0000 U+FEFF) consente al decodificatore di determinare l'ordine di byte e il formato di trasformazione o UTF. Il byte order mark Unicode (BOM) viene serializzato come indicato di seguito (in esadecimale):

  • Ordine byte big endian: 00 00 FE FF

  • Ordine di byte endian piccolo: FF FE 00 00

È possibile creare un'istanza di un oggetto il cui GetPreamble metodo restituisce una UTF32Encoding BOM valida nei modi seguenti:

È consigliabile usare la BOM, poiché fornisce quasi certamente un'identificazione di una codifica per i file che in caso contrario hanno perso riferimento all'oggetto UTF32Encoding , ad esempio, dati Web senza tag o file di testo non contrassegnati correttamente o file di testo casuali archiviati quando un'azienda non ha problemi internazionali o altri dati. Spesso, i problemi utente potrebbero essere evitati se i dati sono contrassegnati in modo coerente e corretto.

Per gli standard che forniscono un tipo di codifica, un BOM è piuttosto ridondante. Tuttavia, può essere utilizzato per consentire a un server di inviare l'intestazione di codifica corretta. In alternativa, può essere utilizzato come fallback in caso contrario, la codifica andrà persa.

L'utilizzo di un BOM presenta alcuni svantaggi. Ad esempio, sapere come limitare i campi del database che utilizzano un BOM può essere difficile. Anche la concatenazione di file può costituire un problema, ad esempio quando i file vengono uniti in modo tale che un carattere non necessario possa finire nel mezzo dei dati. Nonostante i pochi svantaggi, tuttavia, l'utilizzo di un BOM è altamente consigliato.

Per ulteriori informazioni sull'ordine dei byte e sulla byte order mark, vedere lo standard Unicode nella Home Page Unicode.

Importante

Per assicurarsi che i byte codificati vengano decodificati correttamente, è consigliabile anteporre i byte codificati a un preambolo. Si noti che il GetBytes metodo non prependa un BOM a una sequenza di byte codificati. La fornitura di un BOM all'inizio di un flusso di byte appropriato è responsabilità dello sviluppatore.

Si applica a