2011-06-18 16 views
60

Tengo una cadena hexadecimal (por ejemplo, 0CFE9E69271557822FE715A8B3E564BE) y quiero escribirla en un archivo como bytes. Por ejemplo,Escribir bytes en el archivo

Offset  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
00000000 0C FE 9E 69 27 15 57 82 2F E7 15 A8 B3 E5 64 BE .þži'.W‚/ç.¨³åd¾ 

¿Cómo puedo lograr esto usando .NET y C#?

+1

Posiblemente un duplicado de http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c –

+1

@Steven: solo parcial. No es la parte más importante. –

+1

Posible duplicado de [Can a byte \ [\] matriz escrita en un archivo en C#?] (Http://stackoverflow.com/questions/381508/can-a-byte-array-be-written-to-a -file-in-c) (también puede ser solo un duplicado parcial). –

Respuesta

113

Si he entendido bien, esta debería hacer el truco. Necesitará agregar using System.IO en la parte superior de su archivo si todavía no lo tiene.

public bool ByteArrayToFile(string fileName, byte[] byteArray) 
{ 
    try 
    { 
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) 
     { 
      fs.Write(byteArray, 0, byteArray.Length); 
      return true; 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("Exception caught in process: {0}", ex); 
     return false; 
    } 
} 
63

La manera más simple sería convertir su cadena hexadecimal a una matriz de bytes y usar el método File.WriteAllBytes.

Utilizando el método de StringToByteArray()this question, usted haría algo como esto:

string hexString = "0CFE9E69271557822FE715A8B3E564BE"; 

File.WriteAllBytes("output.dat", StringToByteArray(hexString)); 

se incluye el método StringToByteArray a continuación:

public static byte[] StringToByteArray(string hex) { 
    return Enumerable.Range(0, hex.Length) 
        .Where(x => x % 2 == 0) 
        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) 
        .ToArray(); 
} 
+0

Thx, esto funciona bien. ¿Cómo puedo agregar bytes al mismo archivo? (después de la primera "cadena") –

+1

@Robertico: agrega un valor booleano de verdadero al tercer parámetro de WriteAllBytes. ¿Ya descubrió MSDN? Este es el primer enlace de google cuando se busca agregar WriteAllBytes. –

+1

Recibí un error al agregar el valor booleano 'Sin sobrecarga para el método' WriteAllBytes 'toma' 3 'argumentos'. MSDN describe: "Sin embargo, si está agregando datos a un archivo utilizando un bucle, un objeto BinaryWriter puede proporcionar un mejor rendimiento porque solo tiene que abrir y cerrar el archivo una vez". Estoy usando un bucle. Utilizo el ejemplo de @ 0A0D y cambié 'FileMode.Create' a 'FileMode.Append'. –

2

Convierte la cadena hexadecimal en una matriz de bytes.

public static byte[] StringToByteArray(string hex) { 
return Enumerable.Range(0, hex.Length) 
       .Where(x => x % 2 == 0) 
       .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) 
       .ToArray(); 
} 

Crédito: Jared Par

y luego usar WriteAllBytes escribir en el sistema de archivos.

+0

Si hace referencia a una respuesta existente de desbordamiento de pila como respuesta a esta pregunta, entonces es una apuesta bastante segura que esta es una pregunta duplicada y debe marcarse como tal. – ChrisF

+1

En este caso, solo respondió una parte de su pregunta, por lo que sentí que no era necesario marcarla como una estafa. Él solo llegaría hasta la mitad con ese conocimiento. – Khepri

2
 private byte[] Hex2Bin(string hex) { 
     if ((hex == null) || (hex.Length < 1)) { 
      return new byte[0]; 
     } 
     int num = hex.Length/2; 
     byte[] buffer = new byte[num]; 
     num *= 2; 
     for (int i = 0; i < num; i++) { 
      int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber); 
      buffer[i/2] = (byte)num3; 
      i++; 
     } 
     return buffer; 
    } 

     private string Bin2Hex(byte[] binary) { 
     StringBuilder builder = new StringBuilder(); 
     foreach (byte num in binary) { 
      if (num > 15) { 
       builder.AppendFormat("{0:X}", num); 
      } else { 
       builder.AppendFormat("0{0:X}", num);/////// 大于 15 就多加个 0 
      } 
     } 
     return builder.ToString(); 
    } 
+0

Thx, esto también funciona bien. ¿Cómo puedo agregar bytes al mismo archivo? (después de la primera 'cadena') –

Cuestiones relacionadas