我有以下课程:
[Serializable]
public class Writer
{
public char[] FileSignature { get; set; }
public UInt16 FileSourceId { get; set; }
public UInt16 GlobalEncoding { get; set; }
public UInt32 ProjectId1 { get; set; }
public UInt16 ProjectId2 { get; set; }
public UInt16 ProjectId3 { get; set; }
public UInt64 ProjectId4 { get; set; }
public byte Major { get; set; }
public byte Minor { get; set; }
public char[] SystemIdentifier { get; set; }
public Writer()
{
FileSignature = new char[] { 'A', 'A', 'C', 'F' };
FileSourceId = 0;
GlobalEncoding = 0;
ProjectId1 = 0;
ProjectId2 = 0;
ProjectId3 = 0;
ProjectId4 = 0;
Major = 1;
Minor = 0;
var system = "Test 1";
SystemIdentifier = new char[32];
Array.Copy(system.ToCharArray(),SystemIdentifier,14);
}
public byte[] SerializeToBytes()
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
return stream.ToArray();
}
}
public void Write()
{
var m = SerializeToBytes();
using (BinaryWriter writer = new BinaryWriter(new FileStream("DataFile.bin", FileMode.Create, FileAccess.Write)))
{
writer.Write(m);
}
}
}
运行此代码时,我注意到转换为字节数组并写入文件时会跳过某些字节。有人可以帮我确保如何将所有数据成员转换并存储在字节数组中并写入文件。我还附上了创建文件的屏幕截图。
您会看到,仅将47字节的类数据写入文件,而不是58字节: