Convert.FromBase64String(String) Convert.FromBase64String(String) Convert.FromBase64String(String) Convert.FromBase64String(String) Method

Definición

Convierte la cadena especificada, que codifica los datos binarios como dígitos en base 64, en una matriz equivalente de enteros de 8 bits sin signo.Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.

public:
 static cli::array <System::Byte> ^ FromBase64String(System::String ^ s);
public static byte[] FromBase64String (string s);
static member FromBase64String : string -> byte[]
Public Shared Function FromBase64String (s As String) As Byte()

Parámetros

s
String String String String

Cadena que se va a convertir.The string to convert.

Devoluciones

Byte[]

Una matriz de enteros de 8 bits sin signo equivalente a s.An array of 8-bit unsigned integers that is equivalent to s.

Excepciones

La longitud de s, pasando por alto los espacios en blanco, no es cero ni un múltiplo de 4.The length of s, ignoring white-space characters, is not zero or a multiple of 4.

o bien-or- El formato de s no es válido.The format of s is invalid. s contiene un carácter que no es de base 64, más de dos caracteres de relleno o un carácter que no es un espacio en blanco entre los caracteres de relleno.s contains a non-base-64 character, more than two padding characters, or a non-white space-character among the padding characters.

Ejemplos

En el ejemplo siguiente se ToBase64String(Byte[]) usa el método para convertir una matriz de bytes en una cadena UUencoded (base-64) y FromBase64String(String) , a continuación, se llama al método para restaurar la matriz de bytes original.The following example uses the ToBase64String(Byte[]) method to convert a byte array to a UUencoded (base-64) string, and then calls the FromBase64String(String) method to restore the original byte array.

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
Module Example
   Public Sub Main()
       ' Define a byte array.
       Dim bytes As Byte() = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }
       Console.WriteLine("The byte array: ")
       Console.WriteLine("   {0}", BitConverter.ToString(bytes))
       Console.WriteLine()
       
       ' Convert the array to a base 64 string.
       Dim s As String = Convert.ToBase64String(bytes)
       Console.WriteLine("The base 64 string:{1}   {0}{1}", 
                         s, vbCrLf)
       
       ' Restore the byte array.
       Dim newBytes As Byte() = Convert.FromBase64String(s)
       Console.WriteLine("The restored byte array: ")
       Console.WriteLine("   {0}", BitConverter.ToString(newBytes))
       Console.WriteLine()
   End Sub
End Module
' 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

El siguiente es un ejemplo más complejo que crea una matriz de 20 elementos de enteros de 32 bits.The following is a more complex example that creates a 20-element array of 32-bit integers. A continuación, usa BitConverter.GetBytes(Int32) el método para convertir cada elemento en una matriz de bytes, que almacena en la posición adecuada en un búfer llamando Array.Copy(Array, Int32, Array, Int32, Int32) al método.It then uses the BitConverter.GetBytes(Int32) method to convert each element into a byte array, which it stores in the appropriate position in a buffer by calling the Array.Copy(Array, Int32, Array, Int32, Int32) method. A continuación, este búfer se pasa ToBase64String(Byte[]) al método para crear una cadena UUencoded (base-64).This buffer is then passed to the ToBase64String(Byte[]) method to create a UUencoded (base-64) string. A continuación, llama FromBase64String(String) al método para descodificar la cadena UUencoded y BitConverter.ToInt32 llama al método para convertir cada conjunto de cuatro bytes (el tamaño de un entero de 32 bits) en un entero.It then calls the FromBase64String(String) method to decode the UUencoded string, and calls the BitConverter.ToInt32 method to convert each set of four bytes (the size of a 32-bit integer) to an integer. La salida del ejemplo muestra que se ha restaurado correctamente la matriz original.The output from the example shows that the original array has been successfully restored.

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 }
Module Example
   Public Sub Main()
      ' Define an array of 20 elements and display it.
      Dim arr(19) As Integer 
      Dim value As Integer = 1
      For ctr As Integer = 0 To arr.GetUpperBound(0)
         arr(ctr) = value
         value = value * 2 + 1
      Next
      DisplayArray(arr)

      ' Convert the array of integers to a byte array.
      Dim bytes(arr.Length * 4 - 1) As Byte 
      For ctr As Integer = 0 To arr.Length - 1
         Array.Copy(BitConverter.GetBytes(arr(ctr)), 0, 
                    bytes, ctr * 4, 4)
      Next
         
      ' Encode the byte array using Base64 encoding
      Dim base64 As String = Convert.ToBase64String(bytes)
      Console.WriteLine("The encoded string: ")
      For ctr As Integer = 0 To base64.Length \ 50 - 1 
         Console.WriteLine(base64.Substring(ctr * 50, 
                                            If(ctr * 50 + 50 <= base64.Length, 
                                               50, base64.Length - ctr * 50)))
      Next
      Console.WriteLine()
      
      ' Convert the string back to a byte array.
      Dim newBytes() As Byte = Convert.FromBase64String(base64)

      ' Convert the byte array back to an integer array.
      Dim newArr(newBytes.Length\4 - 1) As Integer
      For ctr As Integer = 0 To newBytes.Length \ 4 - 1
         newArr(ctr) = BitConverter.ToInt32(newBytes, ctr * 4)
      Next   
      DisplayArray(newArr)
   End Sub

   Private Sub DisplayArray(arr As Array)
      Console.WriteLine("The array:")
      Console.Write("{ ")
      For ctr As Integer = 0 To arr.GetUpperBound(0) - 1
         Console.Write("{0}, ", arr.GetValue(ctr))
         If (ctr + 1) Mod 10 = 0 Then Console.Write("{0}  ", vbCrLf)
      Next
      Console.WriteLine("{0} {1}", arr.GetValue(arr.GetUpperBound(0)), "}")
      Console.WriteLine()
   End Sub
End Module
' 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 }

Comentarios

sestá formado por dígitos de base 64, caracteres de espacio en blanco y caracteres de relleno finales.s is composed of base-64 digits, white-space characters, and trailing padding characters. Los dígitos de base 64 en orden ascendente de cero son los caracteres en mayúsculas de la "A" a la "Z", los caracteres en minúsculas de la "a" a la "z", los números de "0" a "9" y los símbolos "+" y "/".The base-64 digits in ascending order from zero are the uppercase characters "A" to "Z", lowercase characters "a" to "z", numerals "0" to "9", and the symbols "+" and "/".

Los caracteres de espacio en blanco, y sus nombres Unicode y puntos de código hexadecimal, son Tab (TABULAción de caracteres, U + 0009), nueva línea (avance de línea, U + 000A), retorno de carro (retorno de carro, U + 000D) y en blanco (espacio, u + 0020).The white-space characters, and their Unicode names and hexadecimal code points, are tab (CHARACTER TABULATION, U+0009), newline (LINE FEED, U+000A), carriage return (CARRIAGE RETURN, U+000D), and blank (SPACE, U+0020). Puede aparecer un número arbitrario de caracteres de espacio en blanco s en porque se omiten todos los caracteres de espacio en blanco.An arbitrary number of white-space characters can appear in s because all white-space characters are ignored.

El carácter sin valor, "=", se usa para el relleno final.The valueless character, "=", is used for trailing padding. El final de s puede constar de cero, uno o dos caracteres de relleno.The end of s can consist of zero, one, or two padding characters.

Importante

El FromBase64String método está diseñado para procesar una sola cadena que contiene todos los datos que se van a descodificar.The FromBase64String method is designed to process a single string that contains all the data to be decoded. Para descodificar los datos de caracteres de base 64 de un flujo System.Security.Cryptography.FromBase64Transform , use la clase.To decode base-64 character data from a stream, use the System.Security.Cryptography.FromBase64Transform class.

Se aplica a

Consulte también: