数据(对象)转换成文件格式字节数组Convert Data (object) into file format byte array

- 此内容更新于:2015-01-06
主题:

原文:

I want to save some measured data into a file. For using the file in other application i had to bring the data in to an specific file format. I have a table with the following information:

  • Offset
  • Bytes
  • Type
  • Description

for each Element of the header.

So, i have to convert all the information of my object in this format. Is there a simple way to do that? Is is the right way to make a big byte array and fill this information into the array?

Peter Duniho的回复:在什么格式?你没有提供一个清晰的、精确的、明确的规范所需的格式。# 39;想怀疑你需要“大字节array",但未经明确书面问题,没有人能确定。

(原文:In what format? You have not provided a clear, precise, unambiguous specification of the desired format. It's doubtful you need to "make a big byte array", but without a clearly written question, no one can know for sure.)

解决方案:
如果你想将你的数据和写文件就转换和写它。这是最简单的方法。示例代码: 流可能是文件流。注意BinaryWriter将关闭基地在处理流,但您可以显式地转换数据和自己写基流为字节数组。 其他方式,您可以实现ISerealizable接口。我认为这将是简单的。
原文:

If you want to convert your data and write to a file then just convert and write it. This is the simplest way. Example code:

struct Data
{
    int offset;
    byte[] bytes;
    byte type;
    string description;
}

void WriteDataToStream(Stream outputStream, List<Data> data)
{
    using(var bw = new BinaryWriter(outputStream))
    {
        foreach(var d in data)
        {
            bw.Write(d.offset);
            bw.Write(d.bytes, 0, d.bytes.Length);
            bw.Write(d.type);
            bw.Write(d.description);
        }
    }
}

The stream may be FileStream. Note that the BinaryWriter will close base stream at Dispose, but you can convert data explicitly and write to base stream as byte array by yourself.


Other way, you can implement ISerealizable interface. I think it will be simplest.