Convert.ToBase64String 方法

定义

将 8 位无符号整数数组的值转换为其用 base-64 数字编码的等效字符串表示形式。

重载

ToBase64String(Byte[])

将一个由 8 位无符号整数组成的数组转换为其等效的字符串表示形式,该表示形式使用 base-64 位数字进行编码。

ToBase64String(Byte[], Base64FormattingOptions)

将一个由 8 位无符号整数组成的数组转换为其等效的字符串表示形式,该表示形式使用 base-64 位数字进行编码。 可以指定是否在返回值中插入换行符。

ToBase64String(ReadOnlySpan<Byte>, Base64FormattingOptions)

将指定只读范围内的 8 位无符号整数转换为其等效的字符串表示形式,这些表示形式使用 base-64 数字进行编码。 可以选择指定是否在返回值中插入换行符。

ToBase64String(Byte[], Int32, Int32)

将 8 位无符号整数数组的子集转换为其用 base-64 数字编码的等效字符串表示形式。 参数将子集指定为输入数组中的偏移量以及要转换的数组中的元素数。

ToBase64String(Byte[], Int32, Int32, Base64FormattingOptions)

将 8 位无符号整数数组的子集转换为其用 base-64 数字编码的等效字符串表示形式。 参数将子集指定为输入数组中的偏移量、要转换的数组中的元素数以及是否在返回值中插入换行符。

ToBase64String(Byte[])

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

将一个由 8 位无符号整数组成的数组转换为其等效的字符串表示形式,该表示形式使用 base-64 位数字进行编码。

public static string ToBase64String (byte[] inArray);

参数

inArray
Byte[]

一个由 8 位无符号整数构成的数组。

返回

inArray内容的字符串表示形式(以 base 64 为单位)。

例外

inArray null

示例

以下示例使用 ToBase64String(Byte[]) 方法将字节数组转换为 UUencoded (base-64) 字符串,然后调用 FromBase64String(String) 方法来还原原始字节数组。

using System;

public class Example
{
   public static void Main()
   {
       // Define a byte array.
       byte[] bytes = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
       Console.WriteLine("The byte array: ");
       Console.WriteLine("   {0}\n", BitConverter.ToString(bytes));

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

       // Restore the byte array.
       byte[] newBytes = Convert.FromBase64String(s);
       Console.WriteLine("The restored byte array: ");
       Console.WriteLine("   {0}\n", BitConverter.ToString(newBytes));
   }
}
// The example displays the following output:
//     The byte array:
//        02-04-06-08-0A-0C-0E-10-12-14
//
//     The base 64 string:
//        AgQGCAoMDhASFA==
//
//     The restored byte array:
//        02-04-06-08-0A-0C-0E-10-12-14

下面是一个更复杂的示例,用于创建包含 32 位整数的 20 个元素数组。 然后,它使用 BitConverter.GetBytes(Int32) 方法将每个元素转换为字节数组,该数组通过调用 Array.Copy(Array, Int32, Array, Int32, Int32) 方法存储在缓冲区中的适当位置。 然后将此缓冲区传递给 ToBase64String(Byte[]) 方法,以创建 UUencoded (base-64) 字符串。 然后,它调用 FromBase64String(String) 方法来解码 UUencoded 字符串,并调用 BitConverter.ToInt32 方法将每组四个字节(32 位整数的大小)转换为整数。 该示例的输出显示原始数组已成功还原。

using System;

public class Example
{
   public static void Main()
   {
      // Define an array of 20 elements and display it.
      int[] arr = new int[20];
      int value = 1;
      for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) {
         arr[ctr] = value;
         value = value * 2 + 1;
      }
      DisplayArray(arr);

      // Convert the array of integers to a byte array.
      byte[] bytes = new byte[arr.Length * 4];
      for (int ctr = 0; ctr < arr.Length; ctr++) {
         Array.Copy(BitConverter.GetBytes(arr[ctr]), 0,
                    bytes, ctr * 4, 4);
      }

      // Encode the byte array using Base64 encoding
      String base64 = Convert.ToBase64String(bytes);
      Console.WriteLine("The encoded string: ");
      for (int ctr = 0; ctr <= base64.Length / 50; ctr++)
         Console.WriteLine(base64.Substring(ctr * 50,
                                            ctr * 50 + 50 <= base64.Length
                                               ? 50 : base64.Length - ctr * 50));
      Console.WriteLine();

      // Convert the string back to a byte array.
      byte[] newBytes = Convert.FromBase64String(base64);

      // Convert the byte array back to an integer array.
      int[] newArr = new int[newBytes.Length/4];
      for (int ctr = 0; ctr < newBytes.Length / 4; ctr ++)
         newArr[ctr] = BitConverter.ToInt32(newBytes, ctr * 4);

      DisplayArray(newArr);
   }

   private static void DisplayArray(Array arr)
   {
      Console.WriteLine("The array:");
      Console.Write("{ ");
      for (int ctr = 0; ctr < arr.GetUpperBound(0); ctr++) {
         Console.Write("{0}, ", arr.GetValue(ctr));
         if ((ctr + 1) % 10 == 0)
            Console.Write("\n  ");
      }
      Console.WriteLine("{0} {1}", arr.GetValue(arr.GetUpperBound(0)), "}");
      Console.WriteLine();
   }
}
// The example displays the following output:
// The array:
// { 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023,
//   2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575 }
//
// The encoded string:
// AQAAAAMAAAAHAAAADwAAAB8AAAA/AAAAfwAAAP8AAAD/AQAA/w
// MAAP8HAAD/DwAA/x8AAP8/AAD/fwAA//8AAP//AQD//wMA//8H
//
// The array:
// { 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023,
//   2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575 }

注解

inArray 的元素作为数值,并转换为使用 base-64 数字进行编码的字符串表示形式。

从零开始升序的 base-64 数字是大写字符“A”到“Z”,小写字符“a”到“z”,数字“0”到“9”,符号“+”和“/”。 无值字符“=”用于尾随填充。

重要

ToBase64String 方法旨在处理包含要编码的所有数据的单个字节数组。 若要对流中的数据进行编码,请使用 System.Security.Cryptography.ToBase64Transform 类。

通常,ToBase64String 方法不用于往返 UUEncoded(base-64 编码)字符串。 也就是说,如果通过调用 FromBase64String 方法解码字符串,则通过调用 ToBase64String 方法对返回的字节数组进行编码,生成的字符串不一定与原始字符串相同。 仅当原始字符串是有效的 base-64 编码字符串时,字符串才会往返。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 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, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToBase64String(Byte[], Base64FormattingOptions)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

将一个由 8 位无符号整数组成的数组转换为其等效的字符串表示形式,该表示形式使用 base-64 位数字进行编码。 可以指定是否在返回值中插入换行符。

public static string ToBase64String (byte[] inArray, Base64FormattingOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public static string ToBase64String (byte[] inArray, Base64FormattingOptions options);

参数

inArray
Byte[]

一个由 8 位无符号整数构成的数组。

options
Base64FormattingOptions

InsertLineBreaks 每 76 个字符插入换行符,或 None 插入换行符。

返回

inArray中元素的 base 64 中的字符串表示形式。

属性

例外

inArray null

options 不是有效的 Base64FormattingOptions 值。

示例

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

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 成功还原原始字节数组;转换期间忽略换行符。

注解

inArray 参数的元素作为数值,并转换为 base 64 中的字符串表示形式。

从零开始升序的 base-64 数字是大写字符“A”到“Z”,小写字符“a”到“z”,数字“0”到“9”,符号“+”和“/”。 无值字符“=”用于尾随填充。

重要

ToBase64String 方法旨在处理包含要编码的所有数据的单个字节数组。 若要对流中的数据进行编码,请使用 System.Security.Cryptography.ToBase64Transform 类。

如果 options 参数设置为 InsertLineBreaks 并且转换的输出长度超过 76 个字符,则每 76 个字符插入一个换行符。 换行符定义为回车符(U+000D),后跟换行符(U+000A)。 由于换行符在 base-64 编码中被视为空格字符,因此在将 base-64 编码的字符串转换回字节数组时将被忽略。 向控件或设备(如控制台窗口)显示编码字符串时,换行符非常简单。 有关详细信息,请参阅 RFC 2045“多用途 Internet 邮件扩展”,https://www.rfc-editor.org/

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.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, 4.8.1
.NET Standard 2.0, 2.1

ToBase64String(ReadOnlySpan<Byte>, Base64FormattingOptions)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

将指定只读范围内的 8 位无符号整数转换为其等效的字符串表示形式,这些表示形式使用 base-64 数字进行编码。 可以选择指定是否在返回值中插入换行符。

public static string ToBase64String (ReadOnlySpan<byte> bytes, Base64FormattingOptions options = System.Base64FormattingOptions.None);

参数

bytes
ReadOnlySpan<Byte>

8 位无符号整数的只读范围。

options
Base64FormattingOptions

指定是否在返回值中插入换行符的枚举值之一。 默认值为 None

返回

bytes中元素的 base 64 中的字符串表示形式。 如果 bytes 的长度为 0,则返回空字符串。

例外

options 不是有效的 Base64FormattingOptions 值。

输出长度大于 Int32.MaxValue

适用于

.NET 9 和其他版本
产品 版本
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

ToBase64String(Byte[], Int32, Int32)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

将 8 位无符号整数数组的子集转换为其用 base-64 数字编码的等效字符串表示形式。 参数将子集指定为输入数组中的偏移量以及要转换的数组中的元素数。

public static string ToBase64String (byte[] inArray, int offset, int length);

参数

inArray
Byte[]

一个由 8 位无符号整数构成的数组。

offset
Int32

inArray中的偏移量。

length
Int32

要转换的 inArray 元素数。

返回

从位置 offset开始,inArraylength 元素的 64 个基数中的字符串表示形式。

例外

inArray null

offsetlength 为负数。

-或-

offsetlength 大于 inArray长度。

注解

inArray 的元素被视为数值,并转换为 base 64 中的字符串表示形式。

从零开始升序的 base-64 数字是大写字符“A”到“Z”,小写字符“a”到“z”,数字“0”到“9”,符号“+”和“/”。 无值字符“=”用于尾随填充。

offsetlength 参数是 32 位有符号数字。 offset 参数从零开始。

重要

ToBase64String 方法旨在处理包含要编码的所有数据的单个字节数组。 若要对流中的数据进行编码,请使用 System.Security.Cryptography.ToBase64Transform 类。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 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, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ToBase64String(Byte[], Int32, Int32, Base64FormattingOptions)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

将 8 位无符号整数数组的子集转换为其用 base-64 数字编码的等效字符串表示形式。 参数将子集指定为输入数组中的偏移量、要转换的数组中的元素数以及是否在返回值中插入换行符。

public static string ToBase64String (byte[] inArray, int offset, int length, Base64FormattingOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public static string ToBase64String (byte[] inArray, int offset, int length, Base64FormattingOptions options);

参数

inArray
Byte[]

一个由 8 位无符号整数构成的数组。

offset
Int32

inArray中的偏移量。

length
Int32

要转换的 inArray 元素数。

options
Base64FormattingOptions

InsertLineBreaks 每 76 个字符插入换行符,或 None 插入换行符。

返回

从位置 offset开始,inArraylength 元素的 64 个基数中的字符串表示形式。

属性

例外

inArray null

offsetlength 为负数。

-或-

offsetlength 大于 inArray长度。

options 不是有效的 Base64FormattingOptions 值。

示例

以下示例演示 ToBase64String 方法。 输入分为三个字节(24 位)组。 因此,每个组由四个 6 位数字组成,其中每个数字的范围从十进制 0 到 63。 在此示例中,有 85 个 3 字节组,其余一个字节。 第一组由十六进制值 00、01 和 02 组成,后者生成四个 6 位值,等于十进制 0、0、4 和 2。 这四个值对应于输出开头的 base-64 数字“A”、“A”、“E”和“C”。

如果 3 字节组的整型数不存在,则剩余的字节有效填充为零,形成一个完整的组。 在此示例中,最后一个字节的值是十六进制 FF。 前 6 位等于十进制 63,对应于输出末尾的 base-64 数字“/”,接下来的 2 位填充零,以生成十进制 48,对应于 base-64 数字“w”。 最后两个 6 位值是填充,对应于无值填充字符“=”。

// This example demonstrates the Convert.ToBase64String() and
//                               Convert.FromBase64String() methods

using System;
class Sample
{
    public static void Main()
    {
    byte[] inArray  = new byte[256];
    byte[] outArray = new byte[256];
    string s2;
    string s3;
    string step1 = "1) The input is a byte array (inArray) of arbitrary data.";
    string step2 = "2) Convert a subarray of the input data array to a base 64 string.";
    string step3 = "3) Convert the entire input data array to a base 64 string.";
    string step4 = "4) The two methods in steps 2 and 3 produce the same result: {0}";
    string step5 = "5) Convert the base 64 string to an output byte array (outArray).";
    string step6 = "6) The input and output arrays, inArray and outArray, are equal: {0}";
    int x;
    string nl = Environment.NewLine;
    string ruler1a = "         1         2         3         4";
    string ruler2a = "1234567890123456789012345678901234567890";
    string ruler3a = "----+----+----+----+----+----+----+----+";
    string ruler1b = "         5         6         7      ";
    string ruler2b = "123456789012345678901234567890123456";
    string ruler3b = "----+----+----+----+----+----+----+-";
    string ruler   = String.Concat(ruler1a, ruler1b, nl,
                                   ruler2a, ruler2b, nl,
                                   ruler3a, ruler3b, nl);

// 1) Display an arbitrary array of input data (inArray). The data could be
//    derived from user input, a file, an algorithm, etc.

    Console.WriteLine(step1);
    Console.WriteLine();
    for (x = 0; x < inArray.Length; x++)
        {
        inArray[x] = (byte)x;
        Console.Write("{0:X2} ", inArray[x]);
        if (((x+1)%20) == 0) Console.WriteLine();
        }
    Console.Write("{0}{0}", nl);

// 2) Convert a subarray of the input data to a base64 string. In this case,
//    the subarray is the entire input data array. New lines (CRLF) are inserted.

    Console.WriteLine(step2);
    s2 = Convert.ToBase64String(inArray, 0, inArray.Length,
                                Base64FormattingOptions.InsertLineBreaks);
    Console.WriteLine("{0}{1}{2}{3}", nl, ruler, s2, nl);

// 3) Convert the input data to a base64 string. In this case, the entire
//    input data array is converted by default. New lines (CRLF) are inserted.

    Console.WriteLine(step3);
    s3 = Convert.ToBase64String(inArray, Base64FormattingOptions.InsertLineBreaks);

// 4) Test whether the methods in steps 2 and 3 produce the same result.
    Console.WriteLine(step4, s2.Equals(s3));

// 5) Convert the base 64 string to an output array (outArray).
    Console.WriteLine(step5);
    outArray = Convert.FromBase64String(s2);

// 6) Is outArray equal to inArray?
   Console.WriteLine(step6, ArraysAreEqual(inArray, outArray));
   }

    public static bool ArraysAreEqual(byte[] a1, byte[] a2)
    {
    if (a1.Length != a2.Length) return false;
    for (int i = 0; i < a1.Length; i++)
        if (a1[i] != a2[i]) return false;
    return true;
    }
}
/*
This example produces the following results:

1) The input is a byte array (inArray) of arbitrary data.

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13
14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27
28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63
64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77
78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B
8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F
A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3
B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4 C5 C6 C7
C8 C9 CA CB CC CD CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB
DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF

2) Convert a subarray of the input data array to a base 64 string.

         1         2         3         4         5         6         7
1234567890123456789012345678901234567890123456789012345678901234567890123456
----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+-
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4
OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx
cnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmq
q6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj
5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==

3) Convert the entire input data array to a base 64 string.
4) The two methods in steps 2 and 3 produce the same result: True
5) Convert the base 64 string to an output byte array (outArray).
6) The input and output arrays, inArray and outArray, are equal: True

*/

注解

inArray 参数的元素作为数值,并转换为 base 64 中的字符串表示形式。

从零开始升序的 base-64 数字是大写字符“A”到“Z”,小写字符“a”到“z”,数字“0”到“9”,符号“+”和“/”。 无值字符“=”用于尾随填充。

offsetlength 参数是 32 位有符号数字。 offset 参数从零开始。

重要

ToBase64String 方法旨在处理包含要编码的所有数据的单个字节数组。 若要对流中的数据进行编码,请使用 System.Security.Cryptography.ToBase64Transform 类。

如果 options 参数设置为 InsertLineBreaks 并且转换的输出长度超过 76 个字符,则每 76 个字符插入一个换行符。 换行符定义为回车符(U+000D),后跟换行符(U+000A)。 有关详细信息,请参阅 RFC 2045“多用途 Internet 邮件扩展”,https://www.rfc-editor.org/

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.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, 4.8.1
.NET Standard 2.0, 2.1