向文件写入字节

100

我有一个十六进制字符串(例如0CFE9E69271557822FE715A8B3E564BE),我想将其作为字节写入文件。例如,

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¾

我该如何使用.NET和C#来实现这个?


1
可能是 https://dev59.com/Y3VC5IYBdhLWcg3wYQEp 的重复问题,如何在C#中将字节数组转换为十六进制字符串,反之亦然。 - Steven Mastandrea
1
@Steven:只有部分内容,不是最重要的部分。 - John Doe
1
可能是Can a Byte[] Array be written to a file in C#?的重复问题(也可能只是部分重复)。 - Jeff B
5个回答

178
如果我理解正确的话,这应该可以解决问题。如果你还没有的话,你需要在文件顶部添加using System.IO
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;
    }
}

81

最简单的方法是将您的十六进制字符串转换为字节数组,然后使用File.WriteAllBytes方法。

使用这个问题中的StringToByteArray()方法,您可以像下面这样操作:

string hexString = "0CFE9E69271557822FE715A8B3E564BE";

File.WriteAllBytes("output.dat", StringToByteArray(hexString));
下面是StringToByteArray方法的代码:
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();
}

谢谢,这个很好用。我怎样才能将字节追加到同一个文件中?(在第一个“字符串”之后) - John Doe
1
@Robertico:在WriteAllBytes方法的第三个参数中添加一个布尔值true。您是否已经发现了MSDN?这是搜索WriteAllBytes append时的第一个谷歌链接。 - user195488
1
我收到了一个错误,添加布尔值“没有重载方法'WriteAllBytes'需要'3'个参数”。MSDN描述:“但是,如果您正在使用循环向文件添加数据,则BinaryWriter对象可以提供更好的性能,因为您只需要打开和关闭文件一次。”我正在使用循环。我使用了@0A0D的示例,并将“FileMode.Create”更改为“FileMode.Append”。 - John Doe

3

试试这个:

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();
}

谢谢,这也很好用。我如何将字节附加到同一个文件中?(在第一个“字符串”之后) - John Doe

2
你需要将十六进制字符串转换为字节数组。
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();
}

来源: Jared Par

然后使用WriteAllBytes将其写入文件系统。


1
如果您将现有的Stack Overflow答案作为此问题的答案参考,那么很可能这是一个重复的问题,应该标记为重复。 - ChrisF
1
在这种情况下,它只回答了他问题的一部分,所以我觉得不需要将其标记为重复。他只能凭借那些知识走到一半。 - Khepri

0

这个例子将6个字节读入一个字节数组中,并将其写入另一个字节数组。它对字节执行异或操作,以便写入文件的结果与原始起始值相同。由于它在位置0处写入,所以文件总是6个字节大小。

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        byte[] b1 = { 1, 2, 4, 8, 16, 32 };
        byte[] b2 = new byte[6];
        byte[] b3 = new byte[6];
        byte[] b4 = new byte[6];

        FileStream f1;
        f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);

        // write the byte array into a new file
        f1.Write(b1, 0, 6);
        f1.Close();

        // read the byte array
        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        f1.Read(b2, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b2.Length; i++)
        {
            b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
        // write the new byte array into the file
        f1.Write(b2, 0, 6);
        f1.Close();

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        // read the byte array
        f1.Read(b3, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b3.Length; i++)
        {
            b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);

        // b4 will have the same values as b1
        f1.Write(b4, 0, 6);
        f1.Close();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接