0

I have class representing car with two attributes. I want to convert it to byte[] and save it to binary file.

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

Save method body:

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

If I open file cardata.dat, there is string.

abcd

How to solve this? Thanks.

GoobyPrs
  • 585
  • 2
  • 7
  • 15
  • 1
    Whats to solve? If you write `12` into a file, you probably can't see it in a regular text-editor. Have you tried opening the file in a hex-editor? – Manfred Radlwimmer Nov 15 '17 at 12:34
  • Do you just want to save the class as a file or does it have to be readable? – EpicKip Nov 15 '17 at 12:35
  • Open it in Notepad++ and you'll see the following - abcdFFNULLNULLNULLNULLNULLNULLNULLNULL Note the FF. Your code works fine. – Rich Bryant Nov 15 '17 at 12:43
  • There shouldn't be strings in file if I save it as byte[], I expected some for human not readable data, or am I wrong? I'm not allowed to serialize object, the task is to save data as byte[] to file. – GoobyPrs Nov 15 '17 at 13:01

2 Answers2

1

If you want save to / load from file explicitly (type then id format preserved) you can put it as

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))
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You need to convert/serialize the object Car to a byte array

public static byte[] CarToByteArray(Car car)
{
    BinaryFormatter binf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        binf.Serialize(ms, car);
        return ms.ToArray();
    }
}
Soufiane Tahiri
  • 171
  • 1
  • 15
  • 1
    Technically you just want rep and don't care for the rules :). And I just pointed something out to which you responded a false statement `I answered before it was flagged`. So of course I will respond. And I have plenty of stuff to do but plenty of time to do it, its called time management – EpicKip Nov 15 '17 at 12:44