日期:2014-05-18  浏览次数:21878 次

C#如何將 struct 存入文件同c寫入格式

我在c中有一 struct { char name[32],
  DWORD age;
  }user;

在設置好 struct 的資料後
以 WriteFile(hFile, (LPBYTE)&user,sizeof(user), &retlen, NULL); 寫入文件

現今我要以c#去做和上面一樣的事
要怎麼撰寫才能夠產生一樣格式的文件呢

我試過以序列化方式寫入
但寫入的資料卻都不同
有好的方式可以解決嗎?

  [Serializable]
  internal struct User
  {
  internal string name;
  internal int age;
  }

  User user;
  user.name = tmpName.PadRight(32, ' ');
  user.age = tmpAge;

  BinaryFormatter bf = new BinaryFormatter();
  MemoryStream stream = new MemoryStream();
  bf.Serialize(stream, user);
  byte[] buff = stream.ToArray();

  FileStream fs = new FileStream(writeFileName, FileMode.Create);
  fs.Write(buff, 0, buff.Length);

  fs.Close();



------解决方案--------------------
引入命名空间:
using System;
using System.Runtime.InteropServices;
/// <summary>
/// 结构体转换成字节数组
/// </summary>
/// <param name="structure">结构体</param>
/// <returns>字节数组</returns>
public static Byte[] StructToBytes(Object structure) {
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
Byte[] bytes = new Byte[size];
Marshal.StructureToPtr(structure, buffer, false);
Marshal.Copy(buffer, bytes, 0, size);
Marshal.FreeHGlobal(buffer);
return bytes;
}

/// <summary>
/// 字节数组转换成结构体
/// </summary>
/// <param name="bytes">字节数组</param>
/// <param name="strcutType">结构体类型</param>
/// <returns>结构体</returns>
public static Object BytesToStruct(Byte[] bytes, Type strcutType) {
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, buffer, size);
Object obj = Marshal.PtrToStructure(buffer, strcutType);
Marshal.FreeHGlobal(buffer);
return obj;
}
------解决方案--------------------
C# code

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
        private byte[] name;

        [MarshalAs(UnmanagedType.I4)]
        private int age;

------解决方案--------------------
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct User {

/// char[32]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] name;

/// DWORD->unsigned int
public uint age;
}