Ecrire des octets dans un fichier

J’ai une chaîne hexadécimale (par exemple 0CFE9E69271557822FE715A8B3E564BE ) et je veux l’écrire dans un fichier en tant qu’octets. Par exemple,

 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¾ 

Comment puis-je accomplir cela en utilisant .NET et C #?

Si je vous comprends bien, cela devrait faire l’affaire. Vous aurez besoin d’append en using System.IO en haut de votre fichier si vous ne l’avez pas déjà.

 public bool ByteArrayToFile(ssortingng 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; } } 

Le moyen le plus simple serait de convertir votre chaîne hexadécimale en un tableau d’octets et d’utiliser la méthode File.WriteAllBytes .

En utilisant la méthode SsortingngToByteArray() de cette question , vous feriez quelque chose comme ceci:

 ssortingng hexSsortingng = "0CFE9E69271557822FE715A8B3E564BE"; File.WriteAllBytes("output.dat", SsortingngToByteArray(hexSsortingng)); 

La méthode SsortingngToByteArray est incluse ci-dessous:

 public static byte[] SsortingngToByteArray(ssortingng hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Subssortingng(x, 2), 16)) .ToArray(); } 
  private byte[] Hex2Bin(ssortingng 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.ToSsortingng(); } 

Vous convertissez la chaîne hexadécimale en un tableau d’octets.

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

Crédit: Jared Par

Et puis, utilisez WriteAllBytes pour écrire dans le système de fichiers.