Base64FormattingOptions 枚举

定义

指定相关 ToBase64CharArrayToBase64String 方法是否在其输出中插入换行符。

此枚举支持其成员值的按位组合。

C#
[System.Flags]
public enum Base64FormattingOptions
继承
Base64FormattingOptions
属性

字段

InsertLineBreaks 1

在字符串表示形式中每隔 76 个字符插入换行符。

None 0

不在字符串表示形式中每隔 76 个字符插入换行符。

示例

以下示例使用InsertLineBreaks参数调用Convert.ToBase64String(Byte[], Base64FormattingOptions)该方法,以在编码 100 元素字节数组生成的字符串中插入换行符:

C#
using System;

public class Example
{
   public static void Main()
   {
       // Define a byte array.
       var bytes = new byte[100];
       int originalTotal = 0;
       for (int ctr = 0; ctr <= bytes.GetUpperBound(0); ctr++) {
          bytes[ctr] = (byte)(ctr + 1);
          originalTotal += bytes[ctr];
       }
       // Display summary information about the array.
       Console.WriteLine("The original byte array:");
       Console.WriteLine("   Total elements: {0}", bytes.Length);
       Console.WriteLine("   Length of String Representation: {0}",
                         BitConverter.ToString(bytes).Length);
       Console.WriteLine("   Sum of elements: {0:N0}", originalTotal);
       Console.WriteLine();

       // Convert the array to a base 64 string.
       string s = Convert.ToBase64String(bytes,
                                         Base64FormattingOptions.InsertLineBreaks);
       Console.WriteLine("The base 64 string:\n   {0}\n", s);

       // Restore the byte array.
       Byte[] newBytes = Convert.FromBase64String(s);
       int newTotal = 0;
       foreach (var newByte in newBytes)
          newTotal += newByte;

       // Display summary information about the restored array.
       Console.WriteLine("   Total elements: {0}", newBytes.Length);
       Console.WriteLine("   Length of String Representation: {0}",
                         BitConverter.ToString(newBytes).Length);
       Console.WriteLine("   Sum of elements: {0:N0}", newTotal);
   }
}
// The example displays the following output:
//   The original byte array:
//      Total elements: 100
//      Length of String Representation: 299
//      Sum of elements: 5,050
//
//   The base 64 string:
//      AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5
//   Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZA==
//
//      Total elements: 100
//      Length of String Representation: 299
//      Sum of elements: 5,050

如示例中的输出所示, Convert.FromBase64String 成功还原原始字节数组;换行符在转换期间将被忽略。

注解

Convert.ToBase64CharArrayConvert.ToBase64String方法将 8 位无符号整数数组的值转换为包含 base 64 位数字的等效字符串表示形式。 字符串表示形式可以包含一个或多个换行符,其中换行符定义为回车符, (U+000D) 后跟换行符 (U+000A) 。 由于换行符在 base-64 编码中被视为空白字符,因此在将 base-64 编码的字符串转换回字节数组时将被忽略。 向控件或设备(如控制台窗口)显示编码字符串时,换行符很简单。

None``InsertLineBreaks相互排斥。 因此,尽管 Base64FormattingOptions 枚举用 FlagsAttribute 属性标记,但执行这两个值的按位组合并不有意义。

适用于

产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1