【问题标题】:Save byte array to binary file [duplicate]将字节数组保存到二进制文件[重复]
【发布时间】:2018-04-28 16:26:25
【问题描述】:

我有一个类代表具有两个属性的汽车。我想将其转换为 byte[] 并将其保存为二进制文件。

class Car
    {
        private string type;
        private int id;

        public Car(string paType, int paId)
        {
            type = paType;
            id = paId;
        }

        public byte[] ByteConverter()
        {
            byte[] bArr = new byte[14];

            byte[] hlpType = Encoding.UTF8.GetBytes(this.type);

            byte[] hlpId = BitConverter.GetBytes(this.id);

            hlpType.CopyTo(bArr, 0);
            hlpId.CopyTo(bArr, hlpType.Length);

            return bArr;
        }
    }

保存方法体:

Car c = new Car("abcd", 12);
FileStream fsStream = new FileStream("cardata.bin", FileMode.Create);
fsStream.Write(c.ByteConverter(), 0, 14);
fsStream.Close();

如果我打开文件 cardata.dat,有字符串。

abcd

如何解决这个问题?谢谢。

【问题讨论】:

  • 要解决什么问题?如果您将12 写入文件,您可能无法在常规文本编辑器中看到它。您是否尝试过在十六进制编辑器中打开文件?
  • 您只是想将类保存为文件还是必须可读?
  • 在 Notepad++ 中打开它,您将看到以下内容 - abcdFFNULLNULLNULLNULLNULLNULLNULLNULL 注意 FF。您的代码运行良好。
  • 如果我将它保存为 byte[],文件中不应该有字符串,我希望有一些人类不可读的数据,还是我错了?我不允许序列化对象,任务是将数据作为 byte[] 保存到文件中。

标签: c#


【解决方案1】:

如果你想保存到/从文件中加载显式type然后id格式保留)你可以把它写成

private void SaveToFile(string fileName) {
  File.WriteAllBytes(fileName, Encoding.UTF8
    .GetBytes(type)
    .Concat(BitConverter.GetBytes(id))
    .ToArray());
}

private void LoadFromFile(string fileName) {
   byte[] data = File.ReadAllBytes(fileName);

   type = Encoding.UTF8.GetString(data
     .Take(data.Length - sizeof(int))
     .ToArray());

   id = BitConverter.ToInt32(data, data.Length - sizeof(int))
}

【讨论】:

    【解决方案2】:

    您需要将对象 Car 转换/序列化为字节数组

    public static byte[] CarToByteArray(Car car)
    {
        BinaryFormatter binf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            binf.Serialize(ms, car);
            return ms.ToArray();
        }
    }
    

    【讨论】:

    • 从技术上讲,您只需要代表而不关心规则:)。我刚刚指出了一些事情,你回应了一个错误的陈述I answered before it was flagged。所以我当然会回应。而且我有很多事情要做,但有足够的时间去做,这就是所谓的时间管理
    猜你喜欢
    • 2013-10-27
    • 2021-05-25
    • 2013-10-24
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多