UnicodeEncoding.GetPreamble 方法

定義

如果這個執行個體的建構函式要求位元組順序標記,則會傳回以 UTF-16 格式編碼的 Unicode 位元組順序標記。

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

傳回

Byte[]

如果設定 UnicodeEncoding 物件提供編碼方式,則為包含 Unicode 位元組順序標記的位元組陣列。 否則,這個方法會傳回長度為零的位元組陣列。

範例

下列範例示範如何使用 GetPreamble 方法來擷取實例 UnicodeEncoding 之大端或小位元組順序的 Unicode 位元組順序標記。

using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   array<Byte>^byteOrderMark;
   byteOrderMark = Encoding::Unicode->GetPreamble();
   Console::WriteLine( "Default (little-endian) Unicode Preamble:" );
   IEnumerator^ myEnum = byteOrderMark->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "[{0}]", b );
   }

   Console::WriteLine( "\n" );
   UnicodeEncoding^ bigEndianUnicode = gcnew UnicodeEncoding( true,true );
   byteOrderMark = bigEndianUnicode->GetPreamble();
   Console::WriteLine( "Big-endian Unicode Preamble:" );
   myEnum = byteOrderMark->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "[{0}]", b );
   }
}
using System;
using System.Text;

class UnicodeEncodingExample {
    public static void Main() {
        Byte[] byteOrderMark;
        
        byteOrderMark = Encoding.Unicode.GetPreamble();
        Console.WriteLine("Default (little-endian) Unicode Preamble:");
        foreach (Byte b in byteOrderMark) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine("\n");

        UnicodeEncoding bigEndianUnicode = new UnicodeEncoding(true, true);
        byteOrderMark = bigEndianUnicode.GetPreamble();
        Console.WriteLine("Big-endian Unicode Preamble:");
        foreach (Byte b in byteOrderMark) {
            Console.Write("[{0}]", b);
        }
    }
}
Imports System.Text

Class UnicodeEncodingExample
    
    Public Shared Sub Main()
        Dim byteOrderMark() As Byte
        Dim b As Byte
        
        byteOrderMark = Encoding.Unicode.GetPreamble()
        Console.WriteLine("Default (little-endian) Unicode Preamble:")
        For Each b In  byteOrderMark
            Console.Write("[{0}]", b)
        Next b
        Console.WriteLine(ControlChars.NewLine)
        
        Dim bigEndianUnicode As New UnicodeEncoding(True, True)
        byteOrderMark = bigEndianUnicode.GetPreamble()
        Console.WriteLine("Big-endian Unicode Preamble:")
        For Each b In  byteOrderMark
            Console.Write("[{0}]", b)
        Next b
    End Sub
End Class

下列範例會具現化兩 UnicodeEncoding 個 物件,其中第一個物件未提供 BOM,第二個物件則具現化。 然後它會呼叫 GetPreamble 方法,在撰寫 Unicode 編碼字串之前,先將 BOM 寫入檔案。 如範例的主控台輸出所示,儲存第二個編碼器位元組的檔案比第一個編碼器還多三個位元組。

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

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

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

      ' Use BOM.
      enc = New UnicodeEncoding(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 116 bytes to .\NoPreamble.txt.
'
'       Preamble has 2 bytes
'       Wrote 118 bytes to .\Preamble.txt.

您也可以在主控台視窗中使用 fc 命令來比較檔案,或者您可以在包含十六進位檢視模式的文字編輯器中檢查檔案。 請注意,當檔案在支援 UTF-16 編碼的編輯器中開啟時,不會顯示 BOM。

備註

UnicodeEncoding物件可以提供前置詞,這是位元組陣列,可前置詞到編碼程式所產生的位元組序列。 使用位元組順序標記 (字碼點 U+FEFF) 前置編碼位元組序列,可協助解碼器判斷位元組順序和轉換格式或 UTF。 Unicode 位元組順序標記 (BOM) 序列化,如下所示,以十六進位) (:

  • 大位元組位元組順序:FE FF

  • 小尾位元組順序:FF FE

您可以透過下列方式具現化 UnicodeEncoding 方法傳回有效 BOM 的物件 GetPreamble

建議您使用 BOM,因為它為檔案提供幾乎特定編碼的識別,否則會遺失其編碼的參考,例如未標記或未正確標記的 Web 資料或當企業沒有國際考慮時儲存的隨機文字檔。 如果資料一致且已正確標記,通常可能會避免使用者問題。

對於提供編碼類型的標準,BOM 有點備援。 不過,它可以用來協助伺服器傳送正確的編碼標頭。 或者,當編碼遺失時,它可以用來做為後援。

使用 BOM 有一些缺點。 例如,瞭解如何限制使用 BOM 的資料庫欄位可能很困難。 檔案串連也可能是問題,例如,當檔案合併時,可能會讓不必要的字元最終出現在資料中間。 不過,雖然有幾個缺點,但強烈建議使用 BOM。

重要

若要確保編碼的位元組已正確解碼,您應該在編碼位元組資料流程開頭加上前置詞。 請注意,方法 GetBytes 不會在編碼位元組序列前面加上 BOM;在適當的位元組資料流程開頭提供 BOM 是開發人員的責任。

適用於