當前位置: 首頁>>代碼示例>>C#>>正文


C# UTF8Encoding.GetPreamble方法代碼示例

本文整理匯總了C#中System.Text.UTF8Encoding.GetPreamble方法的典型用法代碼示例。如果您正苦於以下問題:C# UTF8Encoding.GetPreamble方法的具體用法?C# UTF8Encoding.GetPreamble怎麽用?C# UTF8Encoding.GetPreamble使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Text.UTF8Encoding的用法示例。


在下文中一共展示了UTF8Encoding.GetPreamble方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
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();
    }
}
開發者ID:.NET開發者,項目名稱:System.Text,代碼行數:36,代碼來源:UTF8Encoding.GetPreamble

輸出:

UTF8NoPreamble
preamble length: 0
preamble:

UTF8WithPreamble
preamble length: 3
preamble: EF BB BF

示例2: Main

//引入命名空間
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();
   }
}
開發者ID:.NET開發者,項目名稱:System.Text,代碼行數:33,代碼來源:UTF8Encoding.GetPreamble

輸出:

Preamble has 0 bytes
Wrote 57 bytes to NoPreamble.txt.

Preamble has 3 bytes
Wrote 60 bytes to Preamble.txt.


注:本文中的System.Text.UTF8Encoding.GetPreamble方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。