【发布时间】:2012-10-10 18:32:01
【问题描述】:
我有以下结构:
unsafe struct Locomotive
{
public fixed char locotype[6];
public int roadno,HP;
}
我已成功将其写入二进制文件。代码如下:
Locomotive l1 = new Locomotive();
for (int i = 0; i <= 5; i++)
{
l1.locotype[i] = textBox1.Text[i];
}
l1.roadno = int.Parse(textBox2.Text);
l1.HP = int.Parse(textBox3.Text);
BinaryWriter bw = new BinaryWriter(File.Open(@"C:\Documents and Settings\Ruchir Sharma\Desktop\Locodata.bin", FileMode.Append));
IntPtr ip = Marshal.AllocHGlobal(Marshal.SizeOf(l1));
Marshal.StructureToPtr(l1, ip, true);
Byte[] b1 = new Byte[Marshal.SizeOf(l1)];
Marshal.Copy(ip, b1, 0, b1.Length - 1);
bw.Write(b1);
MessageBox.Show("Data written successfully");
Marshal.FreeHGlobal(ip);
bw.Close();
现在,在阅读这个结构时,字符数组,即 locotype[6] 给了我一个问题。我尝试了 BinaryReader.ReadChars() 方法,但它对我不起作用。请帮助我阅读此结构。
【问题讨论】:
-
你手动序列化是有原因的吗?
-
定义“不起作用”——发生了什么?
-
@Marc-AndréJutras 先生,没有具体原因。我读到也可以使用 BinaryFormatter.Serialize 进行序列化,但这仅适用于类。我正在使用结构...
-
@Ruchir 不,不只是为了上课。不过,它可能不喜欢固定缓冲区
-
@MarcGravell 我正在尝试按如下方式读取文件: BinaryReader br = new BinaryReader(File.Open(@"C:\Documents and Settings\Ruchir Sharma\Desktop\Locodata.bin", FileMode.Open,FileAccess.Read)); br.ReadChars(6)); br.ReadInt32(); br.ReadInt32();但是 ReadChars 方法没有正确读取我的数组“locotype”...
标签: c# arrays struct char binaryreader