简体   繁体   中英

C# write class object to binary file in one step

Ok, In C++ I could create a struct object that contains a bunch of value types and when needed write it out to a binary file in a single write statement like this:

struct DataFileHeader {
  unsigned short Id;
  unsigned short Type;
  unsigned int Count;
  unsigned int Offset;
};

...

struct DataFileHeader dataFileHeader;

...
rc = _write(fileHandle, &dataFileHeader, 12);

Is there any way to do that in c#? I've converted my structs to classes in c# and am working with the BinaryFormatter and trying to serialize the object but that adds a bunch of text and other stuff to the stream. I just want to write out the all the value fields in the object. Is this possible or do I have to write out each field on the object separatly?

void Main()
{
    var fileHeader = new DataFileHeader()
    {
        Count = 10,
        Id = 10,
        Offset = 10,
        Type = 10
    };

    Serialize(fileHeader).Dump();
}

// Define other methods and classes here
public byte[] Serialize<TObject>(TObject obj)
{
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    byte[] ret = null;
    using (MemoryStream ms = new MemoryStream())
    {
        binaryFormatter.Serialize(ms, obj);
        ret = ms.ToArray();
    }
    return ret;
}

[Serializable]
public struct DataFileHeader
{
    public short Id;
    public short Type;
    public int Count;
    public int Offset;
};

If that doesn't work I think doing it individually might be the only way.

BitConverter.GetBytes(fileHeader.Count).Concat(BitConverter.GetBytes(fileHeader.Count)).Concat(BitConverter.GetBytes(fileHeader.Count)).Concat(BitConverter.GetBytes(fileHeader.Count)).Dump();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM